如何使用带有 msw 和 react-testing-library 的 react-query 来测试组件?
How to test components using react-query with msw and react-testing-library?
我有一个页面,其中加载了一个下拉组件。该组件调用一个自定义挂钩,该挂钩使用反应查询来获取要显示在下拉列表中的数据。
在初始加载时,此组件处于 loading 状态并呈现加载图标。
当 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 模拟响应数据之后,我的测试也只呈现骨架组件。所以我假设它基本上只等待“isLoading”状态。
it('should load A Selectbox data', async () => {
render(
<QueryClientProvider client={queryClient}>
<SelectItem />
</QueryClientProvider>
);
expect(await screen.getByTestId('select-data')).toBeInTheDocument()
});
请注意,我还实现了 msw 模拟服务器和处理程序来模拟它应该 return 的数据。
顺便说一句,在使用 react 查询之前它就像一个魅力,所以我想我正在监督一些事情。
谢谢!
尝试使用 findByText
(将等待 DOM 元素,返回 Promise
)
expect(await screen.findByText('select-data')).toBeInTheDocument();
我有一个页面,其中加载了一个下拉组件。该组件调用一个自定义挂钩,该挂钩使用反应查询来获取要显示在下拉列表中的数据。 在初始加载时,此组件处于 loading 状态并呈现加载图标。 当 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 模拟响应数据之后,我的测试也只呈现骨架组件。所以我假设它基本上只等待“isLoading”状态。
it('should load A Selectbox data', async () => {
render(
<QueryClientProvider client={queryClient}>
<SelectItem />
</QueryClientProvider>
);
expect(await screen.getByTestId('select-data')).toBeInTheDocument()
});
请注意,我还实现了 msw 模拟服务器和处理程序来模拟它应该 return 的数据。 顺便说一句,在使用 react 查询之前它就像一个魅力,所以我想我正在监督一些事情。
谢谢!
尝试使用 findByText
(将等待 DOM 元素,返回 Promise
)
expect(await screen.findByText('select-data')).toBeInTheDocument();