Search code examples
jestjsreact-router-domreact-testing-library

react jest mock useNavigate()


I am trying to mock the useNavigate hook using Jest. I was able to do it at the top level of my test suit (I also have a custom render with BrowserRouter as a wrapper)

const mockedUsedNavigate = jest.fn();

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

...

expect(mockedUsedNavigate).toHaveBeenCalledWith('myurl/user-1');

My issue is that I want to have this mock available inside the __mocks__ directory so I can use it in other tests as well instead if having to write it again and again. I wasn't able to do it.

Is it possible?


Solution

  • You should be able create a src.setupTests.js file in your project and declare the mock there.

    See Initializing Test Environment

    src/setupTests.js

    export const navigateMock = jest.fn(); // <-- exported for test assertions
    
    jest.mock('react-router-dom', () => ({
      ...(jest.requireActual('react-router-dom') as any),
      useNavigate: () => navigateMock,
    }));
    

    You can then import the exported navigateMock function in test files.