Search code examples
javascriptunit-testingkarma-jasminesinon

How to stub promise.all in sinon


I have a function which has 2 APi calls. Iam destructuring the response and sending each response to different functions to perform some operation. I need to write test case to make API call., fetch response & pass it to respective functions.

This is my code

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);
}

This is my Service call

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;
  }

This is the Test case I written

it('it  should make make API calls for first and second',async () => {
    sinon.stub(componentSerives, 'fetchApiDetails').resolves(bannerResponse);
});

The issue iam facing is., I dont know how to send both first & second APi response in resolves();

on passing it as an array of objects like below., I see firstResponse & secondResponse loading in both objects.

[{firstResponse, secondResponse}]

can you help me how to stub both the APis and assign it to different responses in destructuring?


Solution

  • You are stubbing the wrong thing, according to your own test:

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

    If you are testing fetchApiDetails you cannot stub that function out. That makes no sense! Then you would just be testing your own stub.

    What you need to stub out or inject, are its dependencies: _getfirstApiResponse and _getSecondApiResponse. Stub those out simply by having them just resolve some value:

    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");