0

我对如何通过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。我能做些什么?

先感谢您!

4

1 回答 1

1

解决了这个问题:

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');
        });
    });
});
于 2020-11-02T08:28:13.853 回答