Next.JS & JEST - publicRuntimeConfig 未定义

Nik*_*hil 16 unit-testing reactjs jestjs next.js

使用 next.js 和 Jest 运行单元测试用例时出现“publicRuntimeConfig undefined”错误

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

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

    import { setConfig } from 'next/config';
    import config  from './next.config';
    setConfig(config.publicRuntimeConfig);
    
    Run Code Online (Sandbox Code Playgroud)
  • 我尝试在测试用例文件中使用笑话模拟。

    jest.mock('next/config', () => () => ({
      publicRuntimeConfig: {
        key: 'abc
      }
    }));
    
    Run Code Online (Sandbox Code Playgroud)

小智 17

它适用于我在组件测试用例之前调用 jest.mock,就像您提到的那样:

jest.mock('next/config', () => () => ({
  publicRuntimeConfig: {
    SOME_VARIABLE_HERE: 'whatever-you-want-here'
  }
}))
Run Code Online (Sandbox Code Playgroud)

我不需要创建 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"
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案!但是,如果您想为每个测试运行模型,那么您可能希望将逻辑放在 `jest.setup.js` 中,然后调用 `jest.config.js` ```javascript // jest.config.js module.exports = { setupFiles: ['./jest.setup.js'], } ``` ```javascript // jest.setup.js jest.mock('next/config', ( ) => () => ({ publicRuntimeConfig: { SOME_VARIABLE_HERE: '无论你想要什么' } })) ``` (2认同)

maj*_*our 13

我通过创建一个jest.setup.js文件并添加这行代码解决了这个问题

// jest.config.js

module.exports = {
  // Your config
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
Run Code Online (Sandbox Code Playgroud)

并添加

// jest.setup.js

import { setConfig } from 'next/config'
import config from './next.config'

// Make sure you can use "publicRuntimeConfig" within tests.
setConfig(config)
Run Code Online (Sandbox Code Playgroud)