How to mock useHistory hook in jest?

前端 未结 5 536
無奈伤痛
無奈伤痛 2020-12-17 07:55

I am using UseHistory hook in react router v5.1.2 with typescript? When running unit test, I have got issue.

TypeError: Cannot read property \'history

5条回答
  •  感情败类
    2020-12-17 08:31

    Here's a more verbose example, taken from working test code (since I had difficulty implementing the code above):

    Component.js

      import { useHistory } from 'react-router-dom';
      ...
    
      const Component = () => {
          ...
          const history = useHistory();
          ...
          return (
              <>
                   history.push('/whatever')}>Click me
                  ...
              
          )
      });
    

    Component.test.js

      import { Router } from 'react-router-dom';
      import { act } from '@testing-library/react-hooks';
      import { mount } from 'enzyme';
      import Component from './Component';
      it('...', () => {
        const historyMock = { push: jest.fn(), location: {}, listen: jest.fn() };
        ...
        const wrapper = mount(
          
            
          ,
        ).find('.selector').at(1);
    
        const { onClick } = wrapper.props();
        act(() => {
          onClick();
        });
    
        expect(historyMock.push.mock.calls[0][0]).toEqual('/whatever');
      });
    

提交回复
热议问题