我有一个组件等待资源中的一些数据。我正在使用 React suspense 来显示加载屏幕,直到它得到响应。一切都按预期工作。
但是,在测试时,即使在onGet
中注册,它也永远不会从组件中axiosMock
获取请求。<Cmp />
由于连接错误,测试失败。
import { render, waitFor } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import React, { Suspense } from 'react';
const axiosMock = new MockAdapter(axios, { onNoMatch: 'throwException' });
const wrapPromise = (promise) => {
let status = 'pending';
let result: any;
promise.then(
(r) => {
status = 'success';
result = r;
},
(e) => {
status = 'error';
result = e;
}
);
return {
read() {
return {
status,
result,
};
},
};
};
const fetchData = () => {
return wrapPromise(axios.get('/test').then((r) => r.data));
};
const resource = fetchData();
export const Cmp = () => {
const str = resource.read();
return <h1>{str}</h1>;
};
describe('Main Tests', () => {
beforeAll(() => {
axiosMock.reset();
});
/*
THIS WORKS
*/
it('Sample Request Test', async () => {
axiosMock.onGet('/test').reply(200, 'hello');
expect(await axios.get('/test').then((r) => r.data)).toBe('hello');
});
/*
THIS DOES NOT WORK
*/
it('Component Request Test', async () => {
axiosMock.onGet('/test').reply(200, 'hello');
const { getByText } = render(
<Suspense fallback={<p>Loading...</p>}>
<Cmp />
</Suspense>
);
await waitFor(() => {
return getByText('hello');
});
});
});