问题描述
我有一个有 2 个 API 调用的函数。我正在解构响应并将每个响应发送到不同的函数以执行某些操作。我需要编写测试用例来调用 API。获取响应并将其传递给相应的函数。
这是我的代码
async _fetchComponentDetails() {
const [firstResponse,secondResponse] = await Promise.all([
this._getfirstApiResponse(param1,param2),this._getSecondApiResponse(param1,]);
this.formatFirstApiResult = await componentSerives.formatFirstResponseData(firstResponse);
this.formatSecondApiResult = await componentSerives.formatSecondResponseData(secondResponse);
}
这是我的服务电话
async _getfirstApiResponse(param1,param2) {
const url = 'api/firstApi';
const firstResponse = await componentSerives.fetchApiDetails(url,param1,param2);
return firstResponse;
}
async _getSecondApiResponse(param1,param2) {
const url = 'api/secondApi';
const secondResponse = await componentSerives.fetchApiDetails(url,param2);
return secondResponse;
}
这是我写的测试用例
it('it should make make API calls for first and second',async () => {
sinon.stub(componentSerives,'fetchApiDetails').resolves(bannerResponse);
});
我面临的问题是,我不知道如何在 resolves() 中同时发送第一个和第二个 APi 响应;
将它作为如下对象的数组传递时,我看到 firstResponse 和 secondResponse 在两个对象中加载。
[{firstResponse,secondResponse}]
你能帮助我如何存根两个 API 并在解构时将其分配给不同的响应吗?
解决方法
根据您自己的测试,您存错了:
lazy
如果您正在测试 it('it should make make API calls for first and second',async () => {
,则无法将其存根。这是没有意义的!然后你就可以测试你自己的存根了。
您需要存根或注入的是它的依赖项:fetchApiDetails
和 _getfirstApiResponse
。只需让它们解析一些值即可将它们剔除:
_getSecondApiResponse