【发布时间】: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