【问题标题】:Jest React: How to mock window eventListener set in componentDidMountJest React:如何模拟在 componentDidMount 中设置的窗口 eventListener
【发布时间】:2021-09-28 11:34:51
【问题描述】:

这里我需要在窗口 eventListener 中添加对 handleBeforeUnload 的测试,但我收到错误,我将如何解决它?

   expect(jest.fn())[.not].toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has value: undefined

    map.beforeunload();
    
   expect(wrapper.handleBeforeUnload).toHaveBeenCalled();

我的组件

componentDidMount() {
       window.addEventListener('beforeunload', (event) => {
      this.handleBeforeUnload();
    });
}

handleBeforeUnload () {
}

我的测试规范:

  it('should call handleBeforeUnload', () => {
    const historyMock = { listen: jest.fn(), replace: jest.fn() };
    const map = {};
    window.addEventListener = jest.fn((event, cb) => {
      map[event] = cb;
    });
    const wrapper = shallow(
      <AppRoutes history={historyMock} getDctkConfig={getDctkConfig} />,
    );

    map.beforeunload();

    expect(wrapper.handleBeforeUnload).toHaveBeenCalled();

  });

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    你没有窥探到组件类的.handleBeforeUnload() 方法。您可以通过Component.prototype.handleBeforeUnload 窥探它。另外,你可以模拟.addEventListener()方法的实现,手动调用监听函数。

    index.tsx:

    import React, { Component } from 'react';
    
    export default class AppRoutes extends Component {
      componentDidMount() {
        window.addEventListener('beforeunload', (event) => {
          this.handleBeforeUnload();
        });
      }
    
      handleBeforeUnload() {}
    
      render() {
        return <div>app routes</div>;
      }
    }
    

    index.test.tsx:

    import { shallow } from 'enzyme';
    import React from 'react';
    import AppRoutes from './';
    
    describe('69346085', () => {
      afterEach(() => {
        jest.restoreAllMocks();
      });
      test('should pass', () => {
        const handleBeforeUnloadSpy = jest.spyOn(AppRoutes.prototype, 'handleBeforeUnload');
        jest
          .spyOn(window, 'addEventListener')
          .mockImplementation((type: string, listener: EventListenerOrEventListenerObject) => {
            typeof listener === 'function' && listener({} as Event);
          });
        shallow(<AppRoutes />);
    
        expect(handleBeforeUnloadSpy).toHaveBeenCalled();
      });
    });
    

    测试结果:

    PASS  examples/69346085/index.test.tsx (9.191 s)
      69346085
        ✓ should pass (7 ms)
    
    -----------|---------|----------|---------|---------|-------------------
    File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -----------|---------|----------|---------|---------|-------------------
    All files  |     100 |      100 |     100 |     100 |                   
     index.tsx |     100 |      100 |     100 |     100 |                   
    -----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        9.814 s, estimated 10 s
    

    【讨论】:

      猜你喜欢
      • 2019-07-06
      • 2015-06-25
      • 2019-10-13
      • 2021-02-25
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2017-08-17
      相关资源
      最近更新 更多