如何使用jest配置jsdom

时间:2017-01-18 00:22:55

标签: javascript reactjs jestjs jsdom

我已经在我的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变量但是大叫:

当我致电Cannot read property getItem of undefined

时,

localStorage.getItem(<some item>)

我读了here jes与jsdom一起发送,但我不确定是否需要额外的jsdom依赖。我还读过here,在第一次要求做出反应之前需要加载jsdom。

有没有人知道如何正确配置jsdom jest?

1 个答案:

答案 0 :(得分:1)

jsdom不支持localStorage。看起来您可以使用节点友好的存根,例如'node-localstorage'。请参阅https://github.com/tmpvar/jsdom/issues/1137

上的评论底部

...或者您可以使用https://github.com/letsrock-today/mock-local-storage

之类的东西来嘲笑它

...或滚动自己的模拟,如下所示:How to mock localStorage in JavaScript unit tests?