Search code examples
javascriptangularunit-testingasynchronousjasmine

Jasmine: how to test a Promise.then block?


I want to test a scenario where I have to call a function (from a service which is private readonly) in which there is an async call, then some variables are getting updated etc.

myFunction(param) {
    this.myService
        .serviceFunction(params)
        .then((resp) => {
          let someData = this.transformData(resp);
          this.anotherFunction(someData);
          if (param) {
            // something
          } else {
            // something else
          }
        })
        .catch((e) => {
          // catching errors
        });
  }

In my spec.ts, I tried to mock the serviceFunction call, but it looks like it's not even going in the .then block at all.

spyOn(myService, 'serviceFunction').and.returnValue(Promise.resolve(RESPONSE_MOCK));
expect(component.transformData).toHaveBeenCalled(); // won't work

Do you guys have any tutorial/info to test the .then block in this scenario? I don't have enough knowledge to figure this out myself. Any suggestions would be appreciated.

Thanks!


Solution

  • There are many options available for testing asynchronous code in Angular. Some examples are async/await, fakeAsync/tick and waitForAsync. I will show you examples of async/await/fixture.whenStable() and fakeAsync/tick.

    async/await

    it('does xyz', async () => {
      spyOn(myService, 'serviceFunction').and.returnValue(Promise.resolve(RESPONSE_MOCK));
      // do stuff
      //
      // Wait until all promises have resolved or rejected before continuing.
      await fixture.whenStable();
    
      expect(component.transformData).toHaveBeenCalled();
    });
    

    fakeAsync/tick

    it('does xyz', fakeAsync(() => {
      spyOn(myService, 'serviceFunction').and.returnValue(Promise.resolve(RESPONSE_MOCK));
      // do stuff
      //
      // Wait until all promises have resolved or rejected before continuing.
      tick();
    
      expect(component.transformData).toHaveBeenCalled();
    }));
    

    You can research more about async/await/fixture.whenStable(), waitForAsync and fakeAsync/tick.