【发布时间】:2018-02-16 17:42:27
【问题描述】:
我有一个导入组件的测试,该组件又导入一个帮助文件,该文件使用window 对象提取查询字符串参数。我收到关于window 的以下错误:
FAIL src/js/components/__tests__/Controls.test.jsx
● Test suite failed to run
ReferenceError: window is not defined
Controls.jsx:
import { Unwrapped as Controls } from '../Controls'
describe('<MyInterestsControls />', () => {
it('should render the component with the fixture data', () => {
const component = shallow(
<UnwrappedMyInterestControls
dashboardData={dashboardData}
loadingFlags={{ controls: false }}
/>
)
expect(component).toMatchSnapshot()
})
})
Controls.jsx 导入 ./helpers/services.js,其中包含以下内容:
import * as queryString from 'query-string'
const flag = queryString.parse(window.location.search).flag || 'off'
^^^^^^ this seems to be the problem
我已尝试导入 jsdom
import { JSDOM } from 'jsdom'
并在我的测试文件顶部实现here 提出的解决方案:
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
但是我仍然收到错误,并且似乎 JSDOM 的窗口对象没有暴露给测试。
我怎样才能正确地将window 或document 之类的全局对象暴露给一个笑话测试?
相关的package.json
"scripts": {
"test:watch": "NODE_ENV=test jest --watch"
},
...
"devDependencies": {
...
"jest": "^20.0.4",
"jest-mock": "^21.2.0",
"jsdom": "^11.0.0",
...
},
...
"jest": {
"verbose": true,
"collectCoverageFrom": [
"src/js/helpers/preparePayload.js",
"src/js/components-ni",
"!**/node_modules/**",
"!**/dist/**"
],
"coverageThreshold": {
"global": {
"statements": 50,
"branches": 50,
"functions": 50,
"lines": 75
}
},
"testEnvironment": "jest-environment-node"
}
【问题讨论】:
-
^^ 因为我真的搞砸了markdown 和赏金描述中的链接,这是the enzyme docs的链接
-
你用的是哪个版本的 jest?
-
@JoseAPL jest@^20.0.4, react@16.0.0
-
能否请您添加您的
package.json,默认情况下,jest 使用testEnvironment到类似浏览器的jsdom,因此您不必将jsdom导入到您的单元测试中 -
@JoseAPL 我已经从 package.json 添加了相关部分
标签: javascript reactjs unit-testing jestjs