Due to the build process I'm using to push my app out I'm passing some environment variables in a file after build, which works fine. However it breaks my tests with the following error message:
TypeError: Cannot read property 'DATA' of undefined
57 | Auth: {
58 | oth,
> 59 |
| ^
60 |
61 | identity: checkEnv(window.env.DATA,
62 | process.env.REACT_APP_DATA),
I've tried many solutions but have yet to be able to mock the window.env data, how would I do so?
Create React App allows you to initialize the test environment by including a src/setupTests.js file that "will be automatically executed before running your tests".
Create React App also sets up the testing environment with jsdom which provides the global window object.
You can set window.env in src/setupTests.js and it will be available during your tests:
src/setupTests.js
window.env = {
DATA: 'hi'
}
src/code.js
export const getData = () => window.env.DATA
src/code.test.js
import { getData } from './code';
test('env', () => {
expect(getData()).toBe('hi'); // SUCCESS
})
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