Jest test fails with window is not defined
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.
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": {}
}
}
2021 (Jest 27)
Jest's testEnvironment
default used to be jsdom
. It was changed to node
recently starting with version 27.
You can set testEnvironment: 'jsdom'
in your config file to keep using JSDOM.
However 'node'
seems to be a lot faster, so you should be mocking browser APIs where possible.
https://jestjs.io/blog/2021/05/25/jest-27
npm i jest-environment-jsdom
index.test.tsx
/**
* @jest-environment jsdom
*/