使用Jest和Enzyme在React.Component上测试窗口调整大小处理程序

时间:2018-11-23 12:05:38

标签: javascript reactjs window jestjs enzyme

我正在编写一个在'resize'事件上应用一些逻辑的组件。基本上看起来像这样:

class MyComponent extends React.Component {
    componentDidMount() {
        window.addEventListener('resize', this.handleWindowResize);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.handleWindowResize);
    }

    handleWindowResize = () => console.log('handleWindowResize');
}

测试如下:

it(`should do some stuff on window resize event`, () => {
    const wrapper = mount(<MyComponent />);

    const spy = jest.spyOn(wrapper.instance(), 'handleWindowResize');
    wrapper.update();

    global.dispatchEvent(new Event('resize'));

    expect(spy).toHaveBeenCalled();
});

在我的测试日志中,我收到失败消息:

console.log app/components/MyComponent/index.js:32
  handleWindowResize
console.log app/components/MyComponent/index.js:32
  handleWindowResize
console.log app/components/MyComponent/index.js:32
  handleWindowResize
console.log app/components/MyComponent/index.js:32
  handleWindowResize
console.log app/components/MyComponent/index.js:32
  handleWindowResize

   <CircleGraph /> › should do some stuff on window resize event

    expect(jest.fn()).toHaveBeenCalled()

    Expected mock function to have been called, but it was not called.

      171 |     global.dispatchEvent(new Event('resize'));
      172 | 
    > 173 |     expect(spy).toHaveBeenCalled();
          |                 ^
      174 |   });
      175 | });
      176 | 

因此,在测试过程中将调用原始函数(该函数在原始组件上没有缺陷)可以运行,但在间谍程序上却没有。我究竟做错了什么?

使用react 16.6.0,jest-cli 23.6.0,酶3.7.0

[更新] 我已经在构造函数中使用this.handleWindowResize.bind(this)在原型中添加了经过测试的方法,并这样编写测试:

  it(`should do some stuff on window resize event`, () => {
    const spy = jest.spyOn(CircleGraph.prototype, 'handleWindowResize');
    const wrapper = shallow(<MyComponent />);

    global.dispatchEvent(new Event('resize'));
    wrapper.unmount();

    expect(spy).toHaveBeenCalled();
  });

间谍终于被召唤了。我不确定为什么...

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,困扰了我好几天。
就我而言,我无法解决您的新方法。

但是我刚刚找到了一种解决方案(使用您的较早版本)。

it(`should do some stuff on window resize event`, () => {
    const wrapper = mount(<MyComponent />);
    const spy = jest.spyOn(wrapper.instance(), 'handleWindowResize');

    // set spy to 'resize' listener
    global.addEventListener('resize', spy);
    global.dispatchEvent(new Event('resize'));

    expect(spy).toHaveBeenCalled();
});