使用 moxios 模拟 api 调用

Mock api call using moxios

我还不太熟悉如何通过 moxios 编写单元测试,非常感谢您的帮助。

我的要求如下:

  export const walletRequest = () => {
    return AWAxiosInstance()
        .get(`${AW_BASE_URL}/account/wallet`)
        .then(response => {
            if (response) {
                return formatAccountDetails(response.data);
            }
        })
        .catch(error => {
            return Promise.reject('Error requesting data from Account & Wallet API', error)
        })
}  

所以基本上在上面的函数中,我试图通过 axios 实例检索一些数据。

我的理解是 moxios 被用来模拟 axios 实例,但我不太确定如何为 walletRequest( ) 函数。

我试过的:

import  moxios  from 'moxios'
import { walletRequest } from "../balance";
import AWAxiosInstance from '../../../../core/aw-axios-instance'

const responseMock = { balance: 100 };

describe("services/balance2", () => {

    beforeEach(() => {
        moxios.install(AWAxiosInstance)
    })

    afterEach(() => {
        moxios.uninstall(AWAxiosInstance)
    })

    it("should call the walletRequest and retrieve data", () => {

        moxios.wait(() => {
            const request = moxios.requests.mostRecent()
            request.respondWith({
                status: 200,
                response: {
                    responseMock
                }
            })
        })
        const response = walletRequest().response;
        expect(response).toEqual(responseMock);
    });
});

目前这不起作用,因为 walletRequest() 响应是 undefined。 我能做什么?

提前致谢!

解决了这个问题:

beforeEach(() => {
    moxios.install(AWAxiosInstance)
    formatAccountDetails.mockImplementation( () => responseMock)
})

afterEach(() => {
    moxios.uninstall(AWAxiosInstance)
})

it("should return the data", async () => {

    moxios.wait(() => {
        const request = moxios.requests.mostRecent()
        request.respondWith({
            status: 200,
            response: {
                responseMock
            }
        })
    })

    const response = await walletRequest();
    expect(response).toEqual(responseMock);
});

it('should not recieve response when request is rejected', () => {
    const errorResp = {
        status: 400,
        response: { message: 'invalid data', 
                    data: 'invalid data' }
    };

    const response = walletRequest();

    moxios.wait(async() => {
        let request = moxios.requests.mostRecent();
        request.reject(errorResp);
        response.then((err) => {        
            expect(err).toBe('invalid data');
        });
    });
});