【问题标题】:Mock api call using moxios使用 moxios 模拟 api 调用
【发布时间】:2020-10-31 13:49:54
【问题描述】:

我还不太熟悉如何通过 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。 我能做什么?

提前谢谢你!

【问题讨论】:

  • walletRequest() 是一个承诺,它没有 response 属性。 await 就像您在正常情况下所做的那样。即使那样,也不能保证拥有它,您没有显示 formatAccountDetails。还有一个错误,Promise.reject 有 1 个 arg 并且它丢弃了错误对象。
  • 非常感谢您的评论!这非常有用,我按照您的建议进行了更改,现在效果很好:)

标签: javascript axios jestjs moxios


【解决方案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');
        });
    });
});

【讨论】:

    猜你喜欢
    • 2018-02-21
    • 2020-07-15
    • 1970-01-01
    • 2021-04-18
    • 2017-01-19
    • 2018-06-16
    • 2021-12-30
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多