Home > OS >  Mocking React Query useQueryClient to test cached data
Mocking React Query useQueryClient to test cached data

Time:07-02

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 quantity property
  • makes some API call via React Query useMutation then, 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.

CodePudding user response:

Why would you need to mock setQueryData and getQueryData ? Mocking the network layer with msw should be all you need. If you wrap your rendered hook in a QueryClientProvider with a queryClient, that will be populated with the mocked data returned from msw, and queryClient.getQueryData will be able to read it without mocking it.

  • Related