How to test invalidateQueries has been called after a mutation? #4391
-
I’m using MSW to mock my HTTP requests. This is my simple hook that mutate the data: export const useCreateBatchProductApplication = () => {
const queryClient = useQueryClient();
return useMutation(
(param1: Xpto) =>
makeBackedPostMethod(param1),
{
onSuccess: () => {
queryClient.invalidateQueries(["getAllPastures"]);
},
}
);
}; I want to test if the const createBatchProductApplicationHook = () =>
renderHook(() => useCreateBatchProductApplication(), {
wrapper: createWrapper(),
});
const queryClient = {
invalidateQueries: jest.fn(),
};
const useQueryClient = jest.fn().mockImplementation(() => queryClient);
jest.doMock("react-query", () => ({
...jest.requireActual("react-query”),
useQueryClient,
}));
it("returns the result of useMutation", async () => {
const { result } = createBatchProductApplicationHook();
result.current.mutate({
applicationDate: "2022-09-05",
});
await waitFor(() => expect(result.current.isSuccess).toBe(true)); // this works fine
expect(queryClient.invalidateQueries).toHaveBeenCalled(); // returns 0
}); And I receive the error:
What’s the correct way to test if the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Nothing like a good night’s sleep to get the problems solved automagically 😄 The solution is just mock // useQuery.mock.ts
export const queryClient = {
invalidateQueries: jest.fn(),
};
const useQueryClient = jest.fn().mockImplementation(() => queryClient);
jest.doMock("react-query", () => ({
...jest.requireActual("react-query"),
useQueryClient,
})); and in my test file // ProductApplicationModal.test.ts
import { queryClient } from "shared/hooks/mocks";
…
…
expect(queryClient.invalidateQueries).toHaveBeenCalled(); // success |
Beta Was this translation helpful? Give feedback.
-
Not sure if this is best practice but this has been helping me test things up is to add your dependencies as default parameters. e.g:
then in your test you just pass the jest.fn() directly |
Beta Was this translation helpful? Give feedback.
Nothing like a good night’s sleep to get the problems solved automagically 😄
The solution is just mock
queryClient
in a separated file and then import it at top level of the test file.and in my test file