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);
}
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
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.
}
}
}
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