I have a test that imports a component that in turn imports a helper file that uses the window
object to pull out a query string parameter. I get the following erro
Your problem relies on the configuration.
In the moment you set:
"testEnvironment": "jest-environment-node"
you are changing the default configuration from jest which is browser-like to jest-environment-node
(node-like) meaning that your test will be run under a NodeJs
environment
To solve it either you set your testEnvironment
to jsdom
Or you remove the testEnvironment
from your config so it will take the default value in yourpackage.json
:
...
"jest": {
"verbose": true,
"collectCoverageFrom": [
"src/js/helpers/preparePayload.js",
"src/js/components-ni",
"!**/node_modules/**",
"!**/dist/**"
],
"coverageThreshold": {
"global": {
"statements": 50,
"branches": 50,
"functions": 50,
"lines": 75
}
}
}
testEnvironment
[string] # Default: "jsdom"The test environment that will be used for testing. The default environment in Jest is a browser-like environment through jsdom. If you are building a node service, you can use the node option to use a node-like environment instead.
As I could see, your tests are meant to be run under a browser-like environment.
If you ever need an explicit node environment, better you isolate that case using @jest-environment
:
/**
* @jest-environment node
*/
test('use node in this test file', () => {
expect(true).not.toBeNull();
});
or the other way around if you are meant to run the tests under node
environment
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
With this you can avoid importing jsdom
manually and setting global variables, jsdom
will mock the DOM
implementation automatically.
If you need to change the environment for your tests use the notation @jest-environment