1

我已经尝试了一切enzyme,但是,我在下面找不到测试这些属性的正确方法。请记住,这个组件被包裹在一个虚拟Provider组件中,以便我可以传递必要的道具(即Store)向下进行安装。

1)安装后,在实例上设置一个属性(例如this.property

2) 添加了一个事件监听器

3)在事件监听器上,someFunction正在被调用

class SampleComponent extends Component {

  componentDidMount() {
    this.property = 'property';
    window.addEventListener('scroll', this.someFunction, true);
  }

  someFunction = () => {
    return 'hello';
  };

  render() {
    return <h1>Sample</h1>; 
  }
}

export default EvalueeExposureList;
4

1 回答 1

4

好的,我已经根据与 OP 的讨论更新了我的答案。被测组件有一个 redux 提供者和连接的组件作为子组件,因此我们选择使用酶浅 API。


关于跟踪和测试,addEventListener您可以使用该sinon库创建一个间谍,它暂时“替换” window.addEventListener. 这使您可以访问调用计数以及调用它的参数。

使用酶和摩卡咖啡,我创建了以下测试,这些测试对我来说是通过的。前两个测试涵盖了上述所有案例,为了更好地衡量,我添加了另一个关于如何测试someFunction.

import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow } from 'enzyme';

// Under test.
import SampleComponent from './SampleComponent';

describe('SampleComponent', () => {
  let addEventListenerSpy;

  beforeEach(() => {
    // This replaces the window.addEventListener with our spy.
    addEventListenerSpy = sinon.spy(window, 'addEventListener');
  });

  afterEach(() => {
    // Restore the original function.
    window.addEventListener.restore();
  });

  // This asserts your No 1.
  it(`should set the property`, () => {
    const wrapper = shallow(<SampleComponent />);
    wrapper.instance().componentDidMount(); // call it manually
    expect(wrapper.instance().property).equal('property');
  });

  // This asserts your No 2 and No 3.  We know that by having
  // passed the someFunction as an argument to the event listener
  // we can trust that it is called.  There is no need for us
  // to test the addEventListener API itself.
  it(`should add a "scroll" event listener`, () => {
    const wrapper = shallow(<SampleComponent />);
    wrapper.instance().componentDidMount(); // call it manually
    expect(addEventListenerSpy.callCount).equal(1);
    expect(addEventListenerSpy.args[0][0]).equal('scroll');
    expect(addEventListenerSpy.args[0][1]).equal(wrapper.instance().someFunction);
    expect(addEventListenerSpy.args[0][2]).true;
  });

  it(`should return the expected output for the someFunction`, () => {
    const wrapper = mount(<SampleComponent />);
    expect(wrapper.instance().someFunction()).equal('hello');
  });
});

值得注意的是,我在节点上运行测试,但我的配置中有一个jsdom设置mocha,这可能是负责创建window.addEventListener在我的测试环境中使用的候选。您是通过浏览器还是节点运行测试?如果节点你可能需要做一些类似于我的事情。

于 2016-06-14T17:23:27.460 回答