【问题标题】:Next.JS & JEST - publicRuntimeConfig undefinedNext.JS & JEST - publicRuntimeConfig 未定义
【发布时间】:2020-03-20 17:29:29
【问题描述】:

使用 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。

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

【问题讨论】:

    标签: reactjs unit-testing jestjs next.js


    【解决方案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"
    

    【讨论】:

    • 很好的答案!但是,如果您想为每个测试运行模型,那么您可能希望将逻辑放在 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: 'whatever-you-want-here' } }))
    【解决方案2】:

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

    // jest.config.js
    
    module.exports = {
      // Your config
      setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
    };
    

    并添加

    // jest.setup.js
    
    import { setConfig } from 'next/config'
    import config from './next.config'
    
    // Make sure you can use "publicRuntimeConfig" within tests.
    setConfig(config)
    

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 2021-03-18
      • 1970-01-01
      • 2022-01-06
      • 2021-10-06
      • 2021-10-17
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多