【问题标题】:Mock axios request using jest使用 jest 模拟 axios 请求
【发布时间】:2021-04-20 19:59:42
【问题描述】:

我尝试了以下操作:

jest.mock('axios', () => jest.fn(() => Promise.resolve({ data: testData })));

还尝试添加__mocks__/axios.ts:

export default {
    default: jest.fn(),
    request: jest.fn(),
};

但它会返回:

 TypeError: Cannot read property 'request' of undefined

       7 |     const CLIENT_ROUTER_REQUIRED_HEADER = { 'Content-Type': 'application/json' };
       8 | 
    >  9 |     axiosRetry(axios, { retries: 3 });
         |               ^
      10 | 
      11 |     const responseData = axios({
      12 |         baseURL: baseUrl ? baseUrl : '',

AxiosService.ts

import axios, { AxiosResponse } from 'axios';
import axiosRetry from 'axios-retry';

export const axiosRequest = (data: object, baseUrl?: string): Object => {
    const CLIENT_ROUTER_END_POINT = '/client-router';
    const CLIENT_ROUTER_HTTP_METHOD = 'POST';
    const CLIENT_ROUTER_REQUIRED_HEADER = { 'Content-Type': 'application/json' };

    axiosRetry(axios, { retries: 3 });

    const responseData = axios({
        baseURL: baseUrl ? baseUrl : '',
        url: CLIENT_ROUTER_END_POINT,
        method: CLIENT_ROUTER_HTTP_METHOD,
        headers: CLIENT_ROUTER_REQUIRED_HEADER,
        data: data,
    })
        .then(function (response: AxiosResponse) {
            return response.data;
        })
        .catch((e) => {
            return JSON.stringify(e);
        });
    return responseData;
};

index.ts

import { axiosRequest } from './AxiosService';

export const retrieveDataFromServer = async (
    httpMethod: string,
    gatewayPath: string,
    requestParameters: object,
    baseUrl?: string
): Promise<Object> => {
    const data = {
        httpMethod: httpMethod,
        gatewayPath: gatewayPath,
        requestParameters: requestParameters,
    };

    const responseData = axiosRequest(data, baseUrl);

    return responseData;
};

index.test.ts

import { retrieveDataFromServer } from '../src';

describe('Frontend Client Router React Component', () => {
    test('Retrieve data from job-search endpoint', async () => {
        // The purpose of this test is to show an example on how to use retrieveDataFromServer()
        const data = {
            query: 'strawberry',
            //...other data
        };

        const testData = {
            responseBody:
                '["1", "2", "3"]',
            responseCode: 200,
        };

       jest.mock('axios', () => jest.fn(() => Promise.resolve({ data: testData })));

        expect(
            await retrieveDataFromServer(
                'GET',
                '/search',
                data,
                'http://localhost:8881/'
            )
        ).toMatchObject(testData);
    });
});

【问题讨论】:

  • 您可以通过使用此package 让自己感到头疼。虽然我不确定它如何或是否会在测试环境中与axios-retry 集成。如果它不起作用,您可以看看他们如何test against it 并使用它作为指南。
  • @MattCarlotta 谢谢你,你提到的这个package 拯救了我的一天!

标签: javascript reactjs axios ts-jest


【解决方案1】:

我最后添加了:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);

test('Retrieve data from autocomplete endpoint', async () => {
        const data: AutocompleteData = {
            query: 'strawberry',
        };
        const testData = [
            'strawberry',
        ];
    mock.onPost().replyOnce(200, {
        testData,
    });

    await expect(autocomplete(AutocompleteType.where, data)).resolves.toEqual({
        testData: testData,
    });
}

到我的测试代码。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2022-07-21
    • 2020-07-18
    • 2018-02-24
    • 2020-02-11
    • 2019-05-06
    • 2019-11-14
    • 2020-01-04
    • 2018-12-18
    相关资源
    最近更新 更多