Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get window values in Tests with Enzyme, Jest + Create React App

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?

like image 771
Andrew Obrigewitsch Avatar asked Dec 29 '25 05:12

Andrew Obrigewitsch


1 Answers

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
})
like image 114
Brian Adams Avatar answered Dec 31 '25 17:12

Brian Adams