繁体   English   中英

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

[英]Testing window resize handler on React.Component with Jest & Enzyme

我正在编写一个在“调整大小”事件上应用一些逻辑的组件。 基本上看起来像这样:

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();
  });

间谍终于来了。 我不确定为什么

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

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

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();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM