如果 React 组件需要 jQuery,酶会抛出错误

Enzyme Throws an error if the React Component requires jQuery

我正在尝试使用 Enzyme 的 describeWithDOM()mount() 测试 React 组件的行为。 但是当组件导入 jQuery 我得到这个错误:

错误:jQuery 需要 window 和文档

我知道 Enzyme 在后台使用 jsdom,我一直认为 jsdom 负责处理 window 和文档。但我似乎找不到如何让它们一起工作。

测试代码如下所示:

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.documentglobal.window,如 here.我不使用 jQuery,但我认为这应该提供它正在寻找的 "window with a document"。

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