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

Bar*_*127 7 javascript jquery node.js reactjs enzyme

我正在尝试使用Enzyme describeWithDOM()mount().来测试React Components行为.但是当组件导入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;
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

在按钮onClick方法中,调用了一个jquery函数: $('#inputSelector').focus()

我怎样才能让Enzyme和jsdom在测试中使用jquery?

Tre*_*son 4

describeWithDOM已在当前版本的 Enzyme 中删除,建议在所有测试之前显式初始化global.document和 ,如此处所示global.window所示。我不使用 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...
  }
}
Run Code Online (Sandbox Code Playgroud)

他们使用 Mocha 的--require选项来确保它在任何测试之前执行:

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