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