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

1

18

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

Priceless answered 24/10, 2016 at 11:22 Comment(0)
B
29

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');
    });
}))
Bradski answered 24/10, 2016 at 12:4 Comment(3)
tried this... but its saying that one of my instance variable is undefined..thought I have initialised it as app.edit=false.error is: cannot read property edit of undefined. @peeskilletPriceless
Can you post a complete, minimal test the reproduces the problemBradski
The fail() function is not officially supported by Jest anymore.Credulity

© 2022 - 2024 — McMap. All rights reserved.