【问题标题】:How to stub promise.all in sinon如何在 sinon 中存根 promise.all
【发布时间】:2023-03-05 05:33:01
【问题描述】:

我有一个有 2 个 APi 调用的函数。我正在解构响应并将每个响应发送到不同的函数以执行某些操作。我需要编写测试用例来进行 API 调用。获取响应并将其传递给相应的函数。

这是我的代码

async _fetchComponentDetails() {
    const [firstResponse, secondResponse] = await Promise.all([
      this._getfirstApiResponse(param1, param2),
      this._getSecondApiResponse(param1, param2),
    ]);
    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, param1, 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 并将其分配给不同的响应吗?

【问题讨论】:

    标签: javascript unit-testing karma-jasmine sinon


    【解决方案1】:

    根据你自己的测试,你做错了事:

    it('it  should make make API calls for first and second',async () => {
    

    如果您正在测试fetchApiDetails,则无法将该功能存根。这是没有意义的!然后你就只是在测试你自己的存根。

    您需要存根或注入的是它的依赖项:_getfirstApiResponse_getSecondApiResponse。只需让它们解决一些值即可将它们存根:

    const firstResponse = 42;
    const secondResponse  = -42;
    sinon.replace(componentSerives, '_getfirstApiResponse', sinon.fake.resolves(firstResponse));
    sinon.replace(componentSerives, '_getSecondApiResponse', sinon.fake.resolves(secondResponse  ));
    
    await componentSerives.fetchApiDetails();
    assertEquals(componentSerives.formatFirstApiResult, "Result: 42");
    assertEquals(componentSerives.formatSecondApiResult, "Result: -42");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 2018-10-15
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      相关资源
      最近更新 更多