我正在努力弄清楚如何在我的 React 测试中正确模拟这篇 Axios 帖子。似乎关于如何操作的文档和教程到处都是,没有强烈的共识或最佳实践。
这是我的测试: BatchList.test.js
import React from 'react';
import { setupWorker, rest } from 'msw';
import {
render,
screen,
within,
fireEvent,
waitFor,
} from '@testing-library/react';
import '@testing-library/jest-dom';
import { Provider as AlertProvider } from 'react-alert';
import AlertMUITemplate from 'react-alert-template-mui';
import BatchList from './BatchList';
import mockedAxios from 'axios';
// ... other tests that succeed here ...
// only test that fails here
test('clicking yes and passing back only 2 valid batch numbers should show 2 valid, 2 invalid batch numbers in list', async () => {
// renderBatchListWithNumbers();
const batchList = render(
<AlertProvider template={AlertMUITemplate}>
<BatchList
formulaID={''}
orderID={''}
itemID={''}
formulaResults={[]}
batchNumbers={[
{ BATCH_ID: '987654', ID: '78' },
{ BATCH_ID: '261010', ID: '79' },
{ BATCH_ID: '301967', ID: '80' },
{ BATCH_ID: '445566', ID: '81' },
]}
setBatchNumbers={mockedEmptyFn}
batchNumber={'5'}
setBatchNumber={mockedEmptyFn}
/>
</AlertProvider>
);
const completeButton = batchList.getByText('Complete');
fireEvent.click(completeButton);
const yesButton = batchList.getByText('Yes');
expect(yesButton).toBeInTheDocument();
fireEvent.click(yesButton);
// now we need to figure out mocking the API calls!!!
const data = {
msg: 'fail',
invalidBatchNumbers: ['987654', '445566'],
};
mockedAxios.post.mockResolvedValueOnce({
data: data,
});
await waitFor(() => {
expect(batchList.getByText('987654')).toHaveClass('invalid');
expect(batchList.getByText('261010')).toHaveClass('valid');
});
});
这是我的 __mocks__
文件夹中的 axios.js
:
export default {
post: jest.fn().mockResolvedValue(),
};
所以我在测试中遇到的错误是这样的:抛出:“无法完成所有批处理 - TypeError:(0,_axios.default) 不是函数”
该错误消息字符串来 self 的客户端 API 调用:
export const completeAllBatches = async (
orderID,
itemID,
batchNumbers
) => {
const completeAllBatchesURL =
serverURL + `:${port}/completeAllBatches`;
try {
return await axios({
method: 'post',
url: completeAllBatchesURL,
timeout: shortTimeout,
data: {
orderID,
itemID,
batchNumbers,
},
})
.then((res) => {
return res;
})
.catch((e) => {
return Promise.reject(
'1: Unable to complete all batches - ' + e
);
});
} catch (e) {
return Promise.reject('2: Unable to complete all batches - ' + e);
}
};
最佳答案
我解决了类似的问题,也许这有用?
- 我正在关注这个 tutorial .
为什么会中断?
- 我认为问题在于 typescript 不知道如何处理 axios.post 的一些复杂性。
我没有将默认导入为模拟,而是正常导入
import axios from 'axios'
jest.mock('axios');
然后我对模拟更加明确
const mockedAxios = axios as jest.Mocked<typeof axios>;
let payload:object = {}
const mockedPost = mockedAxios.post.mockReturnValueOnce(payload);
//I highly recommend separating out api client like in the tutorial, then call that api function...
const data = await postBatch();
expect(axios.post).toHaveBeenCalled();
LMK 如果这对你有用,我仍在尝试我的 React 测试模式:)
关于reactjs - 使用 React 测试库/Jest 模拟 axios 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69574437/