How to mock useHistory hook in jest?

前端 未结 5 535
無奈伤痛
無奈伤痛 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:33

    I needed the same when shallowing a react functional component that uses useHistory.

    Solved with the following mock in my test file:

    jest.mock('react-router-dom', () => ({
      useHistory: () => ({
        push: jest.fn(),
      }),
    }));
    

提交回复
热议问题