I have a Login.js inside which I have imported useNavigate from react-router-dom. I called a useNavigate hook at the top level of the functional component like that:
const navigate = useNavigate();
and I use that later like that:
<div onClick={() => navigate("/register")}>Create</div>
I was trying to test this code with jest and react-testing-library, it works fine without a mock but when i try it with mocked useNavigate like that:
test('test navigate to register', () => {
const mockedUsedNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockedUsedNavigate
}));
render(
<Router>
<Login />
</Router>,
);
const registerButton = screen.getByText(/Create/i);
fireEvent.click(registerButton);
expect(mockedUsedNavigate).toHaveBeenCalled();
});
the test is failing.
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
What could be the problem?
Update - my goal is to have 2 unit tests. One for checking whether the function that is called after clicking on a specific div is working properly, (that's just working fine, the test is passing). The other test is to check that after clicking on that specific div a proper function with a proper param will be called. The reason I want to use mock is that I don't want to make any real changes, just to check the call. I do know that the first test already verifies that the proper function was called with the right param, but I kind of want to have as little units tested as possible, so if something breaks it will be clear what went wrong.