How to test if my method throws an observable error in angular2?

Bhushan Gadekar picture Bhushan Gadekar · Oct 24, 2016 · Viewed 11.1k times · Source

I am creating unit-testcases for my angular2 components.

so far test cases are running correctly.

but I am facing issues regarding my asynchronous calls.

For ex. I have following method for creating new user which throws an error if user is already present :

onSubmit():Observable<any> {  
    this._userService.saveUser(this.user).subscribe(
        (response) => {
          this._directoryService.getDirectoryById(this.selectedDirectory._id).subscribe(
            (directory) => {                        
              this.users = directory[0].users;
            },
            (error) => {              
              return error;              
            }
          );
        },
        (error) => {                   
          return error;         
        }
     );
    return ;
}

In my service , I have am throwing an error using following:

if (alreadyExist) {
        let error = "user already exist in database";
        return Observable.throw(error);
}

Now I am expecting this method to throw an error:

expect( function(){ app.onSubmit(); } )
    .toThrow(new Error("User already exist in database"));

Now from my understanding , this test case should be successful , but I am getting below error after my test case fails:

Expected function to throw an exception.

I tried multiple expect blocks:

expect(app.onSubmit()).toThrowError(new Error("User already exist in database"));

but still not getting any success.

any inputs?

thanks

Answer

Paul Samsotha picture Paul Samsotha · Oct 24, 2016

The thing about Observable.throw is that it doesn't actually throw any error. Even if it did, it would be handled internally. expect().toThrowError only catches exceptions that aren't handle and that bubble up to the test.

What Observable.throw does instead is pass the error to the onError callback. So what you should do instead is subscribe the call, and check the error in the callback

it('..', async(() => {
  app.onSubmit().subscribe(
    () => {
      fail('expected error');
    },
    (error) => {
      expect(error).toBe('user already exist in database');
    });
}))