模拟React Query usequeryclient来测试缓存数据

发布于 2025-02-11 16:55:33 字数 1183 浏览 1 评论 0原文

我使用自定义钩子共享增量函数我的应用程序(在购物车中增加数量)。

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 此后,该组件读取React查询卡车缓存

,并使用新数量更新UI。

钩子完成了工作,最终按预期更新了缓存。

现在,我尝试在组件中测试钩子以检查UI是否相应更新。

使用MSW模拟API调用。它的返回值用于更新缓存:

  rest.put(`${api}/carts/1`, (req, res, ctx) => {
    return res(ctx.json({ data: [{ id: 1, quantity: 2 }] }));
  })

我还模拟了React-Query queryClient.setQueryDatagetQueryData函数,以便我可以测试他们的返回值。

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 }] }),
  }),
}));

最后,我测试了应该使用新数量更新的UI,但是模拟的getQueryData始终返回原始数量:1,即使使用多个调用。

现在,我不确定我是否有正确的测试方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海夜未眠 2025-02-18 16:55:33

您为什么需要模拟setqueryDatagetQueryData?使用MSW模拟网络层的内容应该是您所需要的。如果将渲染的钩子包裹在QueryClientProviderqueryClient中,则将用从MSW返回的模拟数据和填充 QueryClient.getQueryData 将能够在不嘲笑它的情况下读取它。

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.

只是我以为 2025-02-18 16:55:33

假设我只想为特定的测试用例模拟GetQueryData,然后将其他功能留下诸如InvalidateQueries,cancelquery和setqueryData之类的其他功能,那么如何修改此模拟功能?
这就是我写的。但是得到这个

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 }] }),
    }),
}));

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 }] }),
    }),
}));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文