How to mock a single named export with Jest
Using jest.mock('module-name')
mocks all exported functions within module-name
. Yet, sometimes, you want to mock the implementation of a very specific function (e.g., to play with the returned value) while letting the rest of the module behave as usual. jest.requireActual('module-name')
allows you to accomplish that:
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn()
}))
In this example, you could mock the behavior of useLocation
while keeping the rest of the functionality (for instance the behavior of useNavigate
, etc.).