【问题标题】:Enzyme Throws an error if the React Component requires jQuery如果 React 组件需要 jQuery,Enzyme 会抛出错误
【发布时间】:2016-05-16 02:41:18
【问题描述】:

我正在尝试使用 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;
    });
  });
}

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

如何让 Enzyme 和 jsdom 在测试中使用 jquery?

【问题讨论】:

  • 问题解决了吗?
  • @pluralism 是的。接受 Trevors 的回答。

标签: javascript jquery node.js reactjs enzyme


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2018-05-03
    • 2016-01-28
    • 2020-01-19
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多