I am getting 'publicRuntimeConfig undefined' error while running unit test cases using next.js and Jest
I am using next 9.1.1.I've tried below solutions but it's not working.
I have set config in jest.setup.js also.Please see below code
import { setConfig } from 'next/config';
import config from './next.config';
setConfig(config.publicRuntimeConfig);
I've tried using jest mock in test case file.
jest.mock('next/config', () => () => ({
publicRuntimeConfig: {
key: 'abc
}
}));
Next. js is a JavaScript framework created by Zeit. It lets you build server-side rendering and static web applications using React. It's a great tool to build your next website. It has many great features and advantages, which can make Nextjs your first option for building your next web application.
In a nutshell, Next. js offers various tools and features to minimize the development process, whereas, React. js has better resources for the front-end development of your mobile and web application.
NextJS is a frontend framework in that it is ReactJS, React-DOM with a NextJS development server for server-side rendering, as such it is not expected for browser-based JavaScript to be necessary.
Next. js is widely used by the biggest and most popular companies all over the world like Netflix, Uber, Starbucks, or Twitch. It's also considered as one of the fastest-growing React frameworks, perfect to work with static sites – which was the hottest topic in the web development world lately.
It works for me calling jest.mock before the Component Test Case like you mentioned:
jest.mock('next/config', () => () => ({
publicRuntimeConfig: {
SOME_VARIABLE_HERE: 'whatever-you-want-here'
}
}))
I didn't need to create a jest.setup or any other stuff. Those are my dependencies:
"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"
I solved this problem by creating a jest.setup.js
file and adding this line of code
// jest.config.js
module.exports = {
// Your config
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
And add
// jest.setup.js
import { setConfig } from 'next/config'
import config from './next.config'
// Make sure you can use "publicRuntimeConfig" within tests.
setConfig(config)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With