我已经在react项目中安装了jest和jsdom,但是在导入使用window.localStorage变量的react组件时遇到了问题。我已经为jsdom添加了一个安装文件,我相信它可以解决这个问题。
下面是我的设置:
package.json中的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变量,但是:
调用localStorage.getItem(<some item>)时的Cannot read property getItem of undefined
我在here上看到jest附带了jsdom,但我不确定是否需要额外的jsdom依赖。我还在here上读到,在第一次需要react之前,需要加载jsdom。
有人知道如何用jsdom正确配置jest吗?
发布于 2017-01-20 04:40:18
jsdom不支持localStorage。看起来你可以使用一个节点友好的存根,比如'node-localstorage‘。请参阅https://github.com/tmpvar/jsdom/issues/1137评论的底部
你可以用像https://github.com/letsrock-today/mock-local-storage这样的东西来模拟它
...or滚动你自己的模拟,如下所示:How to mock localStorage in JavaScript unit tests?
https://stackoverflow.com/questions/41709386
复制相似问题