0

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

To display some cart data, I queryClient.getQueryData(["cart"]) in my component, just before calling the hook. That's why I had to mock the useQueryClient in my test. Maybe It could be simpler if the cart datas were only queried from the hook itself ? I try to find a way to just rely on React Query to display and update my cart datas. But maybe I'm not on the right path.
yeah I don't think its advised to call queryClient.getQueryData during rendering - that's what the useQuery hook is for.
Done ! The test is passing now... except when it fails, occasionally. About one time out of 10, the useQuery on the cart resource returns undefined. It's not related to my original post but if you have an idea. I accept your answer anyway. Thanks for you help !
2

Suppose I just want to mock getQueryData for a particular test case and leave the other functions like invalidateQueries, cancelQuery, and setQueryData as it is, then how can modify this mock function? This is what I wrote. But getting this

TypeError: queryClient.cancelQueries is not a function
jest.mock("@tanstack/react-query", () => ({
    ...jest.requireActual("@tanstack/react-query"),
    useQueryClient: () => ({
        // setQueryData: jest.fn(() => ({ data: [{ label: 'Blue', id: 34 }] })),
        // cancelQueries: jest.fn(),
        // invalidateQueries: jest.fn(),
        ...jest.requireActual("@tanstack/react-query").useQueryClient(),
        getQueryData: jest
            .fn()
            .mockReturnValueOnce({ data: [{ id: 1, quantity: 1 }] })
            .mockReturnValueOnce({ data: [{ id: 1, quantity: 2 }] }),
    }),
}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.