How to mock useHistory hook in jest?

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

    Wearing my politician hat I'll dare to state that you're asking the wrong question.

    It's not useHistory that you want to mock. Instead you'd just want to feed it with history object which you control.

    This also allows you to check for push invocations, just like the 2 top answers (as of writing this).

    If that's indeed the case, createMemoryHistory got your back:

    import {Router} from 'react-router-dom'
    import {createMemoryHistory} from 'history'
    
    test('QuestionContainer should handle navigation', () => {
      const history = createMemoryHistory()
      const pushSpy = jest.spyOn(history, 'push') // or 'replace', 'goBack', etc.
      render(
          
            
          
      )
      userEvent.click(screen.getByRole('button')) // or whatever action relevant to your UI
      expect(pushSpy).toHaveBeenCalled()
    })
    

提交回复
热议问题