我正在使用 React-query 并尝试对其进行测试,在父组件中调用数据并传递给子组件以呈现项目列表。我已经设置了 MSW,但是当我尝试测试时:
const queryClient = new QueryClient()
it('Should give a response', async () => {
render(<QueryClientProvider client={queryClient}><Component /></QueryClientProvider>);
expect(await screen.findByTestId('test-data')).toBeInTheDocument();
})
我明白了:
Unable to find an element by: [data-testid="test-data"]
<body>
<div>
<div
class="mt-5"
>
Loading data ...
</div>
</div>
</body>
父组件是这样的:
const Component1: React.FunctionComponent = () => {
const [fetchData, setFetchData] = React.useState<IData[]>([]);
const queryKey = 'mainData';
const getData = async (): Promise<any> => {
await new Promise(resolve => setTimeout(resolve, 1000))
const response = await axios.get(`xxxxxxx}`).then(res => res.data);
return response;
}
const { data: result, status, isRefetching, error, refetch }: any = useQuery(queryKey, getData,
{
refetchOnWindowFocus: true,
staleTime: 0,
cacheTime: 0,
refetchInterval: 0,
}
);
return (
<>
{status === 'error' && (
<div className="mt-5">{error.message}</div>
)}
{status === 'loading' && (
<div className="mt-5">Loading data ...</div>
)}
{status === 'success' && (
<div className="row dashboard">
<ChildComponent data={fetchData} data-testid="test-data"/> // data passed to this component
<br />
</div>
)}
{isRefetching ? 'Updating...' : null}
</>
)
};
export default Component1;
设置测试:
import '@testing-library/jest-dom';
import { server } from './mocks/server'
// Establish API mocking before all tests.
beforeAll(() => server.listen())
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers())
// Clean up after the tests are finished.
afterAll(() => server.close())
处理程序
import { rest } from 'msw';
export const handlers = [
rest.get('https://xxxxxxxx', (req, res, ctx) => {
return res(
ctx.json([
{
"titleNumber": 499,
"model": "Yes Model",
},
{
"titleNumber": 434,
"model": "No Model",
},
])
);
}),
];
服务器
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
我在错误的地方测试吗?