In case, if you are accessing your application with a http://localhost
prefix, you need to update your jest configuration (in your jest.config.js
) as,
"jest": {
"verbose": true,
"testURL": "http://localhost/"
}
In case you do not already have any jest configuration, just include the configuration in your package.json
. For example:
{
"name": "...",
"description": "...",
...
"jest": {
"verbose": true,
"testURL": "http://localhost/"
}
}
or in jest.config.js
:
module.exports = {
verbose: true,
testURL: "http://localhost/",
...
}
or if you have projects
configured:
module.exports = {
verbose: true,
projects: [{
runner: 'jest-runner',
testURL: "http://localhost/",
// ...
}]
}
I just had this cropping up in a large monorepo (in unit tests, that otherwise wouldn't have required jsdom). Explicitly setting the following in our jest.config.js
(or the package.json
equivalent) also alleviated that issue:
module.exports = {
testEnvironment: 'node'
}
Update: As Nicolas mentioned below (thanks!), you can also add the following flags if you're not using any config files:
jest --testEnvironment node
# or
jest --env=node
You must specify what environment (--env
) are you going to use.
When you run jest
command in the package.json
you should specify the environment (jsdom
or node
). For example:
"scripts": {
"jest": "jest --env=node --colors --coverage test",
"test": "npm run jest"
},
This should work for you!
If you are using jsdom, make sure you include url.
Checkout jsdom repository simple options. https://github.com/jsdom/jsdom#simple-options
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`...`, { url: "https://example.org/" });
The suggestion in the top-rated answer of adding testURL: "http://localhost"
to my Jest config didn't work for me. However, this suggestion from the jsdom GitHub discussion, of passing a URL in when creating the jsdom object, did.
const url = 'http://localhost';
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { url });
To solve the Jest SecurityError: localStorage
error you need to add the jest: { ... }
part to your package.json file
{
"name": "...",
"version": "..",
"main": "..",
"description": "...",
...
"jest": { "verbose": true, "testURL": "http://localhost/" },
}
for me this was solved by upgrading to "jest": "^24.9.0",
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