使用next.js和Jest运行单元测试用例时,出现“ publicRuntimeConfig undefined”错误
我正在使用下一个9.1.1。我已经尝试过以下解决方案,但是它不起作用。
我也在jest.setup.js中设置了配置。请参见下面的代码
import { setConfig } from 'next/config';
import config from './next.config';
setConfig(config.publicRuntimeConfig);
我尝试在测试用例文件中使用开玩笑的模拟。
jest.mock('next/config', () => () => ({
publicRuntimeConfig: {
key: 'abc
}
}));
答案 0 :(得分:1)
它对我有用,就像您提到的那样,在组件测试用例之前调用jest.mock:
jest.mock('next/config', () => () => ({
publicRuntimeConfig: {
SOME_VARIABLE_HERE: 'whatever-you-want-here'
}
}))
我不需要创建jest.setup或其他任何东西。这些是我的依赖项:
"astroturf": "^0.10.4",
"autoprefixer": "^10.0.0",
"axios": "^0.20.0",
"date-fns": "^2.16.1",
"js-cookie": "^2.2.1",
"next": "^9.5.3",
"next-cookies": "^2.0.3",
"node-fetch": "^2.6.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"styled-components": "^5.2.0"
"@babel/preset-env": "^7.11.5",
"@babel/preset-react": "^7.10.4",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.0.4",
"babel-plugin-styled-components": "^1.11.1",
"jest": "^26.4.2"