我试图测试托管在我的Next.js应用程序中的web服务,但是我有一个错误,没有找到Next.js配置。
我的web服务是普通的,存储在pages/api
目录中。由于以下文件,我的API测试获取了一个常量ATTACKS_ENDPOINT
:
/pages/api/tests/api.spec.js
import { ATTACKS_ENDPOINT } from "../config"
...
describe("endpoints", () => {
beforeAll(buildOptionsFetch)
it("should return all attacks for attacks endpoint", async () => {
const response = await fetch(API_URL + ATTACKS_ENDPOINT, headers)
config.js
import getConfig from "next/config"
const { publicRuntimeConfig } = getConfig()
export const API_URL = publicRuntimeConfig.API_URL
我的next.config.js是存在的,并且在启动时被应用程序正确地使用。
当测试运行时,将引发此错误。
TypeError: Cannot destructure property `publicRuntimeConfig` of 'undefined' or 'null'.
1 | import getConfig from "next/config"
2 |
> 3 | const { publicRuntimeConfig } = getConfig()
我寻找解决方案,我找到了这个问题,它谈到了_manually initialise__下一个应用程序。
考虑到我不是测试React组件,而是API web服务,那么如何做到这一点呢?
发布于 2020-02-28 09:41:22
我在Jest测试中遇到的问题是next没有像预期的那样被初始化。我的解决方案是模仿下一个模块..。你可以试试这个:
/** @jest-environment node */
jest.mock('next');
import next from 'next';
next.mockReturnValue({
prepare: () => Promise.resolve(),
getRequestHandler: () => (req, res) => res.status(200),
getConfig: () => ({
publicRuntimeConfig: {} /* This is where you import the mock values */
})
});
在这里阅读有关手动模拟的内容:https://jestjs.io/docs/en/manual-mocks
https://stackoverflow.com/questions/60435277
复制相似问题