Reactjs Next.JS&;JEST-publicRuntimeConfig未定义

Reactjs Next.JS&;JEST-publicRuntimeConfig未定义,reactjs,unit-testing,jestjs,next.js,Reactjs,Unit Testing,Jestjs,Next.js,我在使用next.js和Jest运行单元测试用例时遇到“publicRuntimeConfig undefined”错误 我正在使用next 9.1.1。我尝试了以下解决方案,但它不起作用 我也在jest.setup.js中设置了配置。请看下面的代码 import { setConfig } from 'next/config'; import config from './next.config'; setConfig(config.publicRuntimeConfig); 我已经尝

我在使用next.js和Jest运行单元测试用例时遇到“publicRuntimeConfig undefined”错误

我正在使用next 9.1.1。我尝试了以下解决方案,但它不起作用

  • 我也在jest.setup.js中设置了配置。请看下面的代码

    import { setConfig } from 'next/config';
    import config  from './next.config';
    setConfig(config.publicRuntimeConfig);
    
  • 我已经尝试在测试用例文件中使用jest mock

    jest.mock('next/config', () => () => ({
      publicRuntimeConfig: {
        key: 'abc
      }
    }));
    

在您提到的组件测试用例之前调用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"

回答得好!但是,如果您希望为每个测试运行模型,那么您可能希望将逻辑置于
jest.setup.js
中,然后调用
jest.config.js
javascript//jest.config.js module.exports={setupFiles:['./jest.setup.js'],}/code>
javascript//jest.setup.js jest.mock('next/config',()=>({publicRuntimeConfig:{SOME_VARIABLE_HERE:'which your want HERE'}}}))