Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Testing component - Error when returning Promise.reject from mock

I have a component unit test which isn't handling a promise rejection from a mock in the way I expected it to.

I have this function on a component which sends some data to addUserToOrganisation and handles the Promise that it returns:

 public onSubmit() {
    this.saveStatus = 'Saving';
    this.user = this.prepareSaveUser();
    this._userService.addUserToOrganisation(this.user)
    .then(() => this._router.navigate(['/profile']))
    .catch(error => this.reportError(error));
  }

When testing this component, I have provided a mock for UserService which spies on the addUserToOrganisation endpoint and returns a Promise of some kind:

 mockUserService = jasmine.createSpyObj('mockUserService', ['getOrgId', 'addUserToOrganisation']);
 mockUserService.getOrgId.and.returnValue(Promise.resolve('an id'));
 mockUserService.addUserToOrganisation.and.returnValue(Promise.resolve());

This works fine for happy paths (resolve) - I can test that this._router.navigate() is called and so on. Here is the passing test for this happy path:

it('should navigate to /profile if save is successful', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    component.userForm.controls['firstName'].setValue('John');
    component.userForm.controls['lastName'].setValue('Doe');
    component.userForm.controls['email'].setValue('[email protected]');
    component.onSubmit();

    tick();
    fixture.detectChanges();
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/profile']);
  }));

However, I am having trouble testing the 'sad' path. I alter my mock to return a Promise.reject and, although I have a .catch in onSubmit, I am getting this error:

Error: Uncaught (in promise): no

So that's confusing. Here is my test for this sad path. Note that I change the response of the mock call.

it('should show Failed save status if the save function fails', fakeAsync(() => {
    mockUserService.addUserToOrganisation.and.returnValue(Promise.reject('no'));
    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    component.userForm.controls['firstName'].setValue('John');
    component.userForm.controls['lastName'].setValue('Doe');
    component.userForm.controls['email'].setValue('[email protected]');
    component.onSubmit();

    tick();
    fixture.detectChanges();

    expect(component.saveStatus).toEqual('Failed! no');
  }));

Does anyone have any ideas?

like image 911
dafyddPrys Avatar asked Jun 09 '17 09:06

dafyddPrys


1 Answers

Promise rejections are supposed to be caught, having them unhandled will result in error in Zone.js promise implementation (which is used in Angular applications) and some others (Chrome, core-js promise polyfill, etc).

A rejection should be caught synchronously in order to be considered handled. It is guaranteed this way that an error will always be handled.

This is handled promise:

const p = Promise.reject();
p.catch(err => console.error(err));

This is unhandled promise:

const p = Promise.reject();
setTimeout(() => {
  p.catch(err => console.error(err));
}, 1000);

Even though a rejection will possibly be handled in future, there's no way how implementation can 'know' about that, so a promise is considered unhandled and unhandledrejection event is triggered.

The thing that creates the problem is

tick();
fixture.detectChanges();

If tick() is there 'just in case' and there's no real use of it, it shouldn't be there in the first place. If it should then code needs to be changed to not create unhandled promises:

mockUserService.addUserToOrganisation.and.callFake(() => Promise.reject('no'));
like image 103
Estus Flask Avatar answered Sep 23 '22 19:09

Estus Flask