Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest test fails with window is not defined

I am trying to get started with state of the art web development learning React/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

like image 418
Gunnar Eketrapp Avatar asked Sep 18 '17 08:09

Gunnar Eketrapp


People also ask

How do you set a window to undefined Jest?

You can force window to be undefined in some test files by adding @jest-environment node at the top of the file.

Can you run Jest tests from the terminal?

You can run Jest directly from the CLI (if it's globally available in your PATH , e.g. by yarn global add jest or npm install jest --global ) with a variety of useful options. If you'd like to learn more about running jest through the command line, take a look at the Jest CLI Options page.

What is Jest environment Jsdom?

jsdom is a pure JavaScript implementation of the DOM and browser APIs that runs in node. If you're not using Jest and you would like to run your tests in Node, then you must install jsdom yourself. There's also a package called global-jsdom which can be used to setup the global environment to simulate the browser APIs.


2 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 config I had testEnvironment set to node when it should've been jsdom. For me this setting was located in package.json as defined by the react starter app.

like image 89
JacksonHaenchen Avatar answered Sep 19 '22 15:09

JacksonHaenchen


In your package.json add window like 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": {}    }  }
like image 24
Miguel Cardenas Avatar answered Sep 20 '22 15:09

Miguel Cardenas