When unit testing a utility function that needs access to the publicRuntimeConfig with jest, it throws error Cannot read property 'publicRuntimeConfig' of undefined
For example if i am testing a file that has Contentful stuff in it, and the access token those kind of stuff comes from publicRuntimeConfig, then the test won't past and shows above error.
// next.config.js
module.exports = () => {
return {
publicRuntimeConfig: {
accessToken: '1234565',
}
};
};
// util.js
import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()
const client = createClient({
accessToken: publicRuntimeConfig.accessToken
})
function mathCaculation(){
return 1+1
}
util.test.js
expect(mathCaculation()).toBe(2)
Cannot read property 'publicRuntimeConfig' of undefined
"next": "^7.0.2",
Duplicate of #4024
Specifically: https://github.com/zeit/next.js/issues/4024#issuecomment-386016077
Hi all,
I think I have a different solution/explanation. I too was hit by tests not passing anymore when upgrading from Next.js 7 to 8.
Previously I had a Jest mock in __mocks__/next/config.js. However, it looks to me like even though we do import getConfig from 'next/config', the mock must now be at __mocks__/next-server/config.js. Not entirely quite sure yet why, or what changed recently, but this at least fixes it for me.
The same is true for __mocks__/next/dynamic.js which is now __mocks__/next-server/dynamic.js.
It also applies if you used to do jest.mock('next/config', () => () => ({ publicRuntimeConfig: { ... } })); for instance.
But I think it makes sense:

Maybe the docs should be updated to reflect the new structure and have import getConfig from 'next-server/config'?
@damusnet I occurred into the same problem, thank you so much for spotting this!
@timneutkens should this be documented?
This is something we can solve on the Next.js side of things I think 馃
Most helpful comment
Hi all,
I think I have a different solution/explanation. I too was hit by tests not passing anymore when upgrading from Next.js 7 to 8.
Previously I had a Jest mock in
__mocks__/next/config.js. However, it looks to me like even though we doimport getConfig from 'next/config', the mock must now be at__mocks__/next-server/config.js. Not entirely quite sure yet why, or what changed recently, but this at least fixes it for me.The same is true for
__mocks__/next/dynamic.jswhich is now__mocks__/next-server/dynamic.js.It also applies if you used to do
jest.mock('next/config', () => () => ({ publicRuntimeConfig: { ... } }));for instance.But I think it makes sense:

Maybe the docs should be updated to reflect the new structure and have
import getConfig from 'next-server/config'?