mardi 2 octobre 2018

How to get an async error handler on a observable subscribe to resolve and fully execute in Jest

I currently have a service that I want to test using jest and angular testing tools.

async login() {
  const credentials = this.loginForm.value;

  const loadingSpinner = await this.loadingCtrl.create();
  loadingSpinner.present();

  this.authService.login(credentials.email, credentials.password).subscribe(
  data => {
    loadingSpinner.dismiss();
    this.modalCtrl.dismiss();
  },
  async error => {
    loadingSpinner.dismiss();
    const toast = await this.toastCtrl.create({
      message: 'Failed to log in',
      position: 'top',
      cssClass: 'error-toast'
    });
    toast.present();
  }
 );
}

The code above makes use of the awaits in the error handler. When attempting to use the fakeAsync with tick or flushing all micro tasks, the toastCtrl.create does not fire. When I rewrite the code using the async test the toast.present does not fire but the create does. Below is the test and response.

    it('should make a call to login fire a toast if there is an error', async(() => {
      authService.login.mockReturnValue(throwError({}));
      component.login().then(() => {
        expect(loadingCtrl.create).toHaveBeenCalled();
        expect(loadingInstance.present).toHaveBeenCalled();
        expect(loadingInstance.dismiss).toHaveBeenCalled();
        expect(toastCtrl.create).toHaveBeenCalledWith({
          message: 'Failed to log in',
          position: 'top',
          cssClass: 'error-toast'
        });
        expect(toastInstance.present).toHaveBeenCalled();
      });

The result I get from jest is

 AuthComponent › controller › functions › login › should make a call to login fire a toast if there is an error

Uncaught (in promise): Error: expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called, but it was not called.
Error: expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called, but it was not called.

  132 |               cssClass: 'error-toast'
  133 |             });
> 134 |             expect(toastInstance.present).toHaveBeenCalled();
      |                                           ^
  135 |           });
  136 |         }));
  137 |       });

The question I have is simple, why is the awaits not fully resolving in the tests.

Aucun commentaire:

Enregistrer un commentaire