[英]How to test components using react-query with msw and react-testing-library?
I have a page with a dropdown component being loaded into it.我有一个页面,其中加载了一个下拉组件。 This component calls a customhook that uses react query to get data to show in the dropdown.
这个组件调用一个自定义钩子,它使用反应查询来获取数据以显示在下拉列表中。 On initial load this component is in a loading state and renders a loading icon.
在初始加载时,此组件处于加载state 并呈现加载图标。 When react-query finishes the call successfully the component renders the list of data into the dropdown.
当 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}" />}
/>
</>
);
};
How do I test this correctly?如何正确测试? my test only renders the Skeleton component even after implementing msw to mock the response data.
即使在实现 msw 来模拟响应数据之后,我的测试也只会呈现 Skeleton 组件。 So I assume it basically only awaits the "isLoading" state.
所以我认为它基本上只等待“isLoading”state。
it('should load A Selectbox data', async () => {
render(
<QueryClientProvider client={queryClient}>
<SelectItem />
</QueryClientProvider>
);
expect(await screen.getByTestId('select-data')).toBeInTheDocument()
});
Please note I also implemented msw mock server and handlers to mock the data it should return.请注意,我还实现了 msw 模拟服务器和处理程序来模拟它应该返回的数据。 BTW Before using react query It worked like a charm, so I guess I am overseeing something.
顺便说一句,在使用反应查询之前它就像一个魅力,所以我想我正在监督一些事情。
Thank you!谢谢!
Try using findByText
(will wait for the DOM element, returning a Promise
)尝试使用
findByText
(将等待 DOM 元素,返回Promise
)
expect(await screen.findByText('select-data')).toBeInTheDocument();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.