酶如果React组件需要jQuery,则会引发错误

我试图用Enzyme的describeWithDOM()mount()来testing一个React组件的行为。 但是,当组件导入jQuery我得到这个错误:

错误:jQuery需要一个包含文档的窗口

我知道Enzyme使用引擎盖下的jsdom,我一直以为jsdom照顾窗口和文件。 但我似乎无法find如何让这些工作在一起。

testing代码如下所示:

 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方法的button中调用一个jquery函数: $('#inputSelector').focus()

我如何让酶和jsdom在testing中使用jquery?

describeWithDOM在当前版本的Enzyme中被删除,相反,build议在所有testing之前显式初始化global.documentglobal.window ,如下所示。 我不使用jQuery,但我认为这应该提供正在寻找的“带有文档的窗口”。

Enzyme自己的testing使用的初始化代码在它的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选项来确保它在任何testing之前执行:

mocha --require withDom.js --compilers js:babel-core/register --recursive test/*.js --reporter dot