最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mocking React Query useQueryClient to test cached data - Stack Overflow

programmeradmin0浏览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 ponents 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 ponent 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.

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 ponents 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 ponent 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.

Share Improve this question edited Jun 30, 2022 at 12:49 Tom asked Jun 30, 2022 at 11:16 TomTom 1651 gold badge3 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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 }] }),
    }),
}));
发布评论

评论列表(0)

  1. 暂无评论