我正在尝试使用 Enzyme 的 describeWithDOM()
和 mount()
测试 React 组件的行为。
但是当组件导入 jQuery 时我得到这个错误:
错误:jQuery 需要一个带有文档的窗口
我知道 Enzyme 在后台使用 jsdom,我一直认为 jsdom 负责处理窗口和文档。但我似乎找不到如何让它们一起工作。
测试代码如下所示:
import chai, {expect} from 'chai';
import Select from './Select';
import React, {createElement} from 'react';
import {describeWithDOM, mount} from 'enzyme';
describe('UI Select', () => {
//more shallow tests here
describeWithDOM('User Actions', () => {
it('Toggles the .ui-options menu on button click', () => {
const wrapper = mount(<Select {...baseProps} />);
expect(wrapper.state().open).to.not.be.ok;
wrapper.find('button').simulate('click');
expect(wrapper.state().open).to.be.ok;
});
});
}
在按钮的 onClick 方法中调用了一个 jquery 函数:$('#inputSelector').focus()
如何让Enzyme和jsdom在测试中使用jquery?
最佳答案
describeWithDOM
已在当前版本的 Enzyme 中删除,建议显式初始化 global.document
和 global.window
在所有测试之前,如图所示 here .我不使用 jQuery,但我认为这应该提供它正在寻找的“带有文档的窗口”。
Enzyme 自己的测试使用的初始化代码在其 withDom.js
中可用。文件:
if (!global.document) {
try {
const jsdom = require('jsdom').jsdom; // could throw
const exposedProperties = ['window', 'navigator', 'document'];
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js',
};
} catch (e) {
// jsdom is not supported...
}
}
他们使用 Mocha 的 --require
选项来确保它在任何测试之前执行:
mocha --require withDom.js --compilers js:babel-core/register --recursive test/*.js --reporter dot
关于javascript - 如果 React 组件需要 jQuery,Enzyme 会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35235700/