Mocking a useMutation and checking number of calls of mutate #2505
Replies: 3 comments 4 replies
-
the docs don't suggest to mock the actual mutation function, but to rather mock the outgoing network requests. You can do that with something like nock or I would suggest mock-service-worker. |
Beta Was this translation helpful? Give feedback.
-
I found this solution:
|
Beta Was this translation helpful? Give feedback.
-
I managed to test it from a screen by using the following: vi.mock('@application/hooks/useTodos')
vi.mock('@application/hooks/useHistories')
const mockUseTodos = vi.mocked(useTodos)
const mockUseHistories = vi.mocked(useHistories)
mockUseTodos.mockReturnValue({
data: todosMock,
error: null,
isLoading: false,
create: mockUseMutationResult<Todo>(),
remove: { mutate: removeMock },
update: mockUseMutationResult<UpdateTodoProps>(),
}) But we get then a Typescript issue:
We managed to mock the export const mockUseMutationResult = <TVariables,>(): UseMutationResult<
void,
Error,
TVariables,
unknown
> => ({
mutate: vi.fn() as UseMutateFunction<void, Error, TVariables, unknown>,
mutateAsync: vi.fn(),
data: undefined,
error: null,
isError: false,
isIdle: true,
isLoading: false,
isPaused: false,
isSuccess: false,
reset: vi.fn(),
status: 'idle',
variables: undefined,
context: undefined,
failureCount: 0,
}) But we have another issue yet:
What's the best way to mock it so we don't get typing issues? |
Beta Was this translation helpful? Give feedback.
-
I'm having some trouble checking my mutation is actually being launched with Testing Library and Jest.
Consider the following hook:
I'm currently mocking it as:
I then click a button to start my mutation in my test (I've verified this is happening by console.logging), but the following happens:
Any tips on how to handle this? The docs give examples for testing queries, but there's no examples for mutations.
Beta Was this translation helpful? Give feedback.
All reactions