簡體   English   中英

如果React組件需要jQuery,則會引發錯誤

[英]Enzyme Throws an error if the React Component requires jQuery

我正在嘗試使用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?

describeWithDOM已在酶的當前版本中被刪除,取而代之的建議明確初始化global.documentglobal.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...
  }
}

他們使用Mocha的--require選項來確保它在任何測試之前執行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM