Jest SecurityError: localStorage is not available for opaque origins

前端 未结 12 519
礼貌的吻别
礼貌的吻别 2021-01-30 19:24

When I want to run my project with the command npm run test, I get the error below. What is causing this?

FAIL
● Test suite failed to run

SecurityE         


        
相关标签:
12条回答
  • 2021-01-30 19:38

    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/" },
    
    }
    
    0 讨论(0)
  • 2021-01-30 19:49

    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
    
    0 讨论(0)
  • 2021-01-30 19:49

    for me this was solved by upgrading to "jest": "^24.9.0",

    0 讨论(0)
  • 2021-01-30 19:51

    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!

    0 讨论(0)
  • 2021-01-30 19:52

    If you are using jsdom you have to change your setup for tests like this:

    const { JSDOM } = require('jsdom');
    const jsdom = new JSDOM('<!doctype html><html><body></body></html>', {
      url: 'http://localhost/',
    });```
    
    0 讨论(0)
  • 2021-01-30 19:56

    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 });
    
    0 讨论(0)
提交回复
热议问题