0

I am mocking useNavigate to test my login page redirect works after login. But I got this reference error.

ReferenceError: Cannot access 'mockedUsedNavigate' before initialization

      12 | jest.mock('react-router-dom', () => ({
      13 |   ...jest.requireActual('react-router-dom'),
    > 14 |   useNavigate: () => mockedUsedNavigate,

I've looked through the forum and aware it might be the jest.mock() hoisted to the top but I did define mockedUsedNavigate before the mock.

// mock useNavigate
const mockedUsedNavigate = jest.fn()

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useNavigate: () => mockedUsedNavigate, 
}))

code for my login page:

  const dispatch = useDispatch()
  const navigate = useNavigate()

  const handleSubmit = e => {
    e.preventDefault()
    if (isSignup) {
      dispatch(signup(formData, navigate))
    } else {
      dispatch(signin(formData, navigate))
    }
  }

However, the same test code works for my other project.

jeffdeng
  • 61
  • 4
  • Can you share the code that shows how the ```mockedUsedNavigate``` variable is used? – Ovidijus Parsiunas May 22 '22 at 14:16
  • _Don't_ mock useNavigate (in general, don't mock what you don't own); test the behaviour not the implementation. See e.g. https://stackoverflow.com/a/65275037/3001761. – jonrsharpe May 22 '22 at 15:10
  • @jonrsharpe Thanks for the suggestion. I've tried what you suggested and it works if I put `navigate('/')` after the dispatch in the same component. However, the original idea was passing `navigate` in my login dispatch actions and excute `navigate('/')` after getting server response. How do you handle situation like this, where `navigate('/')` is not in the rendered component? Hope I'm explained well.. – jeffdeng May 23 '22 at 10:13
  • @OvidijusParsiunas I used this line `await waitFor(() => expect(mockedUsedNavigate).toHaveBeenCalled())` – jeffdeng May 23 '22 at 10:15

0 Answers0