我正在努力弄清楚如何在我的反应测试中正确地模拟这个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__文件夹中的__mocks__:
export default {
    post: jest.fn().mockResolvedValue(),
};所以我在测试中遇到的错误是:thrown: "Unable to complete all batches - TypeError: (0 , _axios.default) is not a function"
该错误消息字符串来自我的客户端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);
    }
};发布于 2021-10-15 03:21:02
我解决了一个类似的问题,也许这是有用的?
为什么要休息?
我不是像模仿的那样导入默认值,而是按正常方式导入。
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();如果这对你有用的话,我还在玩我的反应测试模式:)
https://stackoverflow.com/questions/69574437
复制相似问题