Mocking imported modules correctly with Vitest and React #5809
-
|
The documentation might be a bit insufficient, so I think if you answer my question, it would help the others for the future reference. Please refer to https://vitest.dev/guide/mocking.html Setup: React Vite TypeScript SPA All deps versions are ^, so they might in fact be higher atm. react 18.2.0 Case:
This obviously results with the: I wanted to Mock the useNavigate to return vi.fn(), to avoid that error. However, trying multiple scenarios didn't help, namely: Solution 1 (not working): Solution 2 (not working): Solution 3 (not working): Solution 4 (not working): Doing exactly the same above mocking with Solution 5 (not working): Providing a global Solution 6 (not working): All above + explicit mocking inside my test using Summary: There is in fact a possibility that I am a complete moron. But there is also a possibility that something is not right with the mocking in Vitest. It basically doesn't work as I expect. Doesn't seem to work at all as a matter of fact. Please provide me some insight as to what I'm doing wrong or what I should be doing right. Much appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
What do you mean by "not working"? Is all of them still causing vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn(),
}));To keep other exports, you will need Can you setup a reproduction so we can see the exact setup? |
Beta Was this translation helpful? Give feedback.
What do you mean by "not working"? Is all of them still causing
Error: useNavigate() may be used only in the contextor different errors?If you only need to mock
import { useNavigate } from 'react-router-dom', then technically this should suffice:To keep other exports, you will need
importOriginalas shown in https://vitest.dev/api/vi.html#vi-mockCan you setup a reproduction so we can see the exact setup?