Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jest

ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jest. Error come from following code export function. Any one met this type of error and solved it?

import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';

import rootReducer from '../modules/rootReducer';

    export function injectAsyncReducers(asyncReducers) {
  const injectReducers = Object.keys(asyncReducers).reduce((all, item) => {
    if (store.asyncReducers[item]) {
      delete all[item];
    }

    return all;
  }, asyncReducers);

  store.asyncReducers = Object.assign({}, store.asyncReducers, injectReducers);
  replaceReducers(rootReducer);
}
like image 714
khalifathul Avatar asked Dec 24 '22 12:12

khalifathul


2 Answers

This error usually comes out when you aren't using the right testEnviremoent configuration for jest, ins this case it should be jsdom (you can take a look at it here: https://github.com/tmpvar/jsdom). You can configure it in your package.json file like this:

"jest": {"testEnvironment": "node"}

If you're using create-react-app you test script should be like this:

"test": "react-scripts test --env=jsdom"

Or you can see more options for the testEviroment config here: https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string

like image 144
Andres Mateo Otalvaro Avatar answered Dec 31 '22 03:12

Andres Mateo Otalvaro


Well, there is no window, because you run jest on terminal, not browser. You should define window as a global variable manually.

package.json

...
"jest": {
    "globals": {
      "window": {
        // whatever you need, put here manually.
      }
    }
  }
like image 26
arikanmstf Avatar answered Dec 31 '22 02:12

arikanmstf