簡體   English   中英

如何使用帶有 msw 和 react-testing-library 的 react-query 測試組件?

[英]How to test components using react-query with msw and react-testing-library?

我有一個頁面,其中加載了一個下拉組件。 這個組件調用一個自定義鈎子,它使用反應查詢來獲取數據以顯示在下拉列表中。 在初始加載時,此組件處於加載state 並呈現加載圖標。 當 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”state。

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

請注意,我還實現了 msw 模擬服務器和處理程序來模擬它應該返回的數據。 順便說一句,在使用反應查詢之前它就像一個魅力,所以我想我正在監督一些事情。

謝謝!

嘗試使用findByText (將等待 DOM 元素,返回Promise

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM