我想测试API调用和返回的数据,这些数据应该在我的功能组件中显示。我有一个组件,当它第一次被加载时,以及当某些事情发生变化时,如输入时,会调用API。
我有一个 useEffect
这样调用API。
useEffect(() => {
const query = queryString;
const apiRequest = async () => {
try {
setIsFetching(true);
const response = await getData(query, page);
setData(response.data);
} catch (error) {
// Do some error
console.log('error');
} finally {
setIsFetching(false);
}
};
apiRequest();
}, [queryString, page]);
getData
是一个 axios
函数,就像这样。
let getDataRequest;
const getData = (searchQuery = null, page = PAGE, size = PAGE_SIZE) => {
if (getDataRequest) getDataRequest.cancel();
getDataRequest = axios.CancelToken.source();
return axios.get('url_to_api', {
params: {
page,
searchQuery,
size,
},
cancelToken: getDataRequest.token,
});
};
当我试图测试这个组件的时候,我遇到了一个错误 When testing, code that causes React state updates should be wrapped into act(...):
我一直在努力遵循 第一环节 还 第二环节 第三环节 和更多的页面,但仍然没有运气。
这里是我仍然看到错误的一个测试版本。
it('should render data', async () => {
let container;
act(async () => {
await getData.mockResolvedValueOnce({
data: { things: data, meta: { current_page: 1 } },
});
container = render(<Component />);
});
await waitFor(() => container.queryByText('Text I would expect after api call'));
})
我也试过在我的测试文件中模拟这个函数,就像这样。
import { getData } from './dataAccess';
const mockedData = { data: { things: data } };
jest.mock('./api', () => ({
getData: jest
.fn()
.mockImplementation(() => new Promise(resolve => resolve(mockedData))),
}));
我使用的是 import { act } from 'react-dom/test-utils';
与酶和jest。我也在使用 '@testing-library/react';