Jest test fails with "window is not defined"

Viewed 63436

I am trying to get started with state-of-the-art web development learning React and Redux.

Right now I am stuck at getting tests running. For some reason, Jest fails with

Task :frontend:test
yarn jest v1.0.2
$ "/Users/gunnar/git/app.oakstair.se/frontend/node_modules/.bin/jest"
FAIL src/containers/App/App.test.js
  ● Test suite failed to run

 ReferenceError: window is not defined

  at Object.<anonymous> (config/polyfills.js:18:1)
  at next (native)
  at process._tickCallback (internal/process/next_tick.js:109:7)

I have googled for a while without any success...

This is my starting test.js

And this my App test code

5 Answers

I had the same issue and I do not believe modifying globals is the way to do it.

The issue was because in my Jest configuration I had testEnvironment set to node when it should've been jsdom. For me, this setting was located in file package.json as defined by the React starter app.

In your package.json file, add window like a global. Something like this:

"jest": {
  "verbose": true,
  "preset": "react-native",
  "setupFiles": ["./jest/setup.js"],
  "testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?react-native|lottie-react-native)"
  ],
  "globals": {
    "window": {}
  }
}

2021 (Jest 27)

Jest's testEnvironment default used to be jsdom. It was changed to node starting with version 27.

You can set testEnvironment: 'jsdom' in your configuration file to keep using JSDOM.

However, 'node' seems to be a lot faster, so you should be mocking browser APIs where possible.

Jest 27: New Defaults for Jest, 2021 edition

npm i jest-environment-jsdom

File index.test.tsx

/**
 * @jest-environment jsdom
 */

If you want to keep testEnvironment set to node, you can configure a global window in your jest.config.js/ts and then mock what you need in your test cases.

It works fine as long as you don't need any advanced features. It is the same answer as some of the high rated previous ones, but including some examples.

import type {Config} from '@jest/types';

const config: Config.InitialOptions = {
  ...jestConfig,
  testEnvironment: "node",
  globals: {
    window: {
     location: {}
    }
  }
};

export default config;

SomeTestCase.spec.ts

test('Is correct href', () => {
  window.location.href = 'https://somedomain.com';
  expect(window.location.href).toBe('https://somedomain.com');
})
Related