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

Enzyme Throws an error if the React Component requires jQuery

本文关键字:出错 错误 jQuery React 如果 组件 Enzyme      更新时间:2023-09-26

我正在尝试使用酶的describeWithDOM()mount()来测试反应组件的行为。但是当组件导入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.documentglobal.window,如下所示。我不使用 jQuery,但我认为这应该提供它正在寻找的"带有文档的窗口"。

酶自己的测试使用的初始化代码在其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

相关文章: