问题描述
我已经在我的react项目中安装了jest和jsdom,但是在导入使用window.localStorage
变量的react组件时遇到了问题.我为jsdom添加了一个设置文件,我相信它将解决该问题.
I have installed jest and jsdom into my react project but I am having problems with importing a react component that uses the window.localStorage
variable. I have added a setup file for jsdom that I believed would solve the problem.
这是我的设置:
jest配置
"jest": {
"verbose": true,
"testEnvironment": "jsdom",
"testURL": "http://localhost:8080/Dashboard/index.html",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
"^.+\\.jsx$": "<rootDir>/node_modules/babel-jest"
},
"unmockedModulePathPatterns": [
"node_modules/react/",
],
"moduleFileExtensions": [
"js",
"jsx",
"json",
"es6"
]
}
setup.js
import jsdom from 'jsdom';
const DEFAULT_HTML = '<html><body></body></html>';
global.document = jsdom.jsdom(DEFAULT_HTML);
global.window = document.defaultView;
global.navigator = window.navigator;
global.localStorage = window.localStorage;
test.js
'use strict';
import setup from './setup';
import React from 'react';
import jsdom from 'jsdom';
import Reportlet from '../components/Reportlet.jsx';
it('Ensures the react component renders', () => {
});
我的reportlet组件使用localStorage变量,但大喊:
My reportlet component uses the localStorage variable but yells:
Cannot read property getItem of undefined
当我呼叫localStorage.getItem(<some item>)
我在此处读到,jest与jsdom一起提供但是我不确定是否需要额外的jsdom依赖关系.我还阅读了此处,需要先加载jsdom,然后才需要对第一个做出反应时间.
I read here that jest comes shipped with jsdom but I am not sure if I need the extra jsdom dependency or not. I also read here that jsdom needs to be loaded before requiring react for the first time.
有人知道如何正确地用jsdom配置玩笑吗?
Does anyone know how to configure jest with jsdom correctly?
推荐答案
jsdom不支持localStorage.看起来您可以使用"node-localstorage"之类的节点友好型存根.请参见 https://github.com/tmpvar/jsdom/issues/1137
jsdom does not support localStorage. It looks like you can use a node-friendly stub like 'node-localstorage'. See bottom of comments at https://github.com/tmpvar/jsdom/issues/1137
...或者您可以使用 https://github之类的东西来模拟它. com/letsrock-today/mock-local-storage
...or you can mock it with something like https://github.com/letsrock-today/mock-local-storage
...或像下面这样滚动自己的模拟程序:如何在JavaScript单元测试中模拟localStorage?
...or roll your own mock like seen here: How to mock localStorage in JavaScript unit tests?
这篇关于我如何用玩笑配置jsdom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!