【问题标题】:How to test components using react-query with msw and react-testing-library?如何使用带有 msw 和 react-testing-library 的 react-query 测试组件?
【发布时间】:2021-05-27 15:31:23
【问题描述】:

我有一个正在加载下拉组件的页面。这个组件调用一个自定义钩子,它使用反应查询来获取数据以显示在下拉列表中。 在初始加载时,此组件处于 正在加载 状态并呈现加载图标。 当 react-query 成功完成调用时,组件将数据列表呈现到下拉列表中。

const SelectItem = ({ handleSelectChange, selectedItem }) => {
  
  const { data, status } = useGetData(url, 'myQueryKey');

  if (status === 'loading') {
    return <RenderSkeleton />;
  }

  if (status === 'error') {
    return 'An Error has occured';
  }

  return (
    <>
      <Autocomplete
        options={data}
        getOptionLabel={(option) => `${option.name}`}
        value={selectedItem}
        onChange={(event, newValue) => {
          handleSelectChange(newValue);
        }}
        data-testid="select-data"
        renderInput={(params) => <TextField {...params}" />}
      />
    </>
  );
};

如何正确测试? 即使在实现 msw 来模拟响应数据之后,我的测试也只会呈现 Skeleton 组件。所以我假设它基本上只等待“isLoading”状态。

it('should load A Selectbox data', async () => {
  render(
    <QueryClientProvider client={queryClient}>
      <SelectItem />
    </QueryClientProvider>
  );
  expect(await screen.getByTestId('select-data')).toBeInTheDocument()
});

请注意,我还实现了 msw 模拟服务器和处理程序来模拟它应该返回的数据。 顺便说一句,在使用 react 查询之前它就像一个魅力,所以我想我正在监督一些事情。

谢谢!

【问题讨论】:

  • 你的模拟数据返回了一个超时的承诺?您是否尝试过使用来自 react-testing-library 的findByText(将等待 DOM 元素); expect(await screen.findByText('select-data')).toBeInTheDocument();
  • 谢谢,这确实解决了!认为这是一个愚蠢的错误!
  • 不错!刚刚发布了答案!

标签: reactjs jestjs react-testing-library react-query msw


【解决方案1】:

尝试使用findByText(将等待DOM元素,返回Promise

expect(await screen.findByText('select-data')).toBeInTheDocument();

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2019-08-29
    • 2021-02-11
    • 2021-02-28
    • 2019-05-21
    • 1970-01-01
    • 2021-11-30
    • 2020-03-22
    • 2019-11-11
    相关资源
    最近更新 更多