【问题标题】:Jest mocked api call failing to return data开玩笑的 api 调用无法返回数据
【发布时间】:2022-11-12 08:59:36
【问题描述】:

我有以下自定义 React 钩子:

...
    useEffect(() => {
        const handleMonitoringData = async (isDefaultProduct?: boolean) => {
            const result = await getMonitoringData(intermediaryId);
            if (result) {
                const sortedResult = result.sort((a, b) =>
                    a.product?.name > b.product?.name ? 0 : -1
                );

                setMonitoringData(sortedResult);
                if (isDefaultProduct) selectProduct(sortedResult[0]);
            }
        };

        if (isSuperUser) {
            setMonitoringData([]);
            selectProduct(null);

            if (hasRendered) {
                handleMonitoringData();
            } else {
                toggleHasRendered(true);
            }
        } else {
            handleMonitoringData(true);
        }
    }, [intermediaryId]);
...

以及我尝试测试初始监控数据负载(确切地说是 else 语句 => handleMonitoringData(true)),如下所示:

jest.mock('@api/Monitoring', () => ({
    getMonitoringData: () => [mockedData],
}));

describe('useFundRaising custom hook', () => {
    it('should work', async () => {
        function TestComponent() {
            const { monitoringData } = useFundRaising();

            return <div>{console.log('data: ', monitoringData)}</div>;
        }

        const res = await render(<TestComponent />);
    });
});

getMonitoringData:

export const getMonitoringData = async (
    intermediaryId?: string
): Promise<MonitoringData[]> => {
    const URL = intermediaryId
        ? `${MONITORING_DATA_URL}/${intermediaryId}`
        : MONITORING_DATA_URL;

    const result = await Http.get<MonitoringData[]>(URL);
    return result;
};

测试当前失败:

[![在此处输入图像描述][2]][2]

【问题讨论】:

    标签: javascript reactjs promise jestjs


    【解决方案1】:

    你有没有试过这样模拟:

    const mockGetMonitoringData = jest.fn().mockResolvedValue(mockedData);
    
    jest.mock('@api/Monitoring', () => ({
      getMonitoringData: () => mockGetMonitoringData(),
    }));
    

    因为getMonitoringDataasync 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      相关资源
      最近更新 更多