I use a custom hook to share an increment function accross my app (it increments quantities in a shopping cart).
What that function does :
- gets a data object from a React Query cache
- increments the data
quantityproperty - makes some API call via React Query
useMutationthen, on success, updates the React Query cache
After that, the components reads the React Query cart cache and updates the UI with the new quantity.
The hook does the job and finally the cache is updated as expected.
Now, I try to test the hook in a component to check that the UI is updated accordingly.
The API call is mocked using msw. Its returned value is used to update the cache :
rest.put(`${api}/carts/1`, (req, res, ctx) => {
return res(ctx.json({ data: [{ id: 1, quantity: 2 }] }));
})
I also mocked the react-query queryClient.setQueryData and getQueryData functions so I can test their returns values.
jest.mock("react-query", () => ({
...jest.requireActual("react-query"),
useQueryClient: () => ({
setQueryData: jest.fn(),
getQueryData: jest
.fn()
.mockReturnValueOnce({ data: [{ id: 1, quantity: 1 }] })
.mockReturnValueOnce({ data: [{ id: 1, quantity: 2 }] }),
}),
}));
Finally, I test the UI that should updates with the new quantity, but the mocked getQueryData always return the original quantity: 1, even with multiple call.
Now I'm not sure I have the right approach for that test.