Reputation: 315
I'm newbie in RxJS world and I have a problem with unit-test for one of my method.
In my Angular componen I have a login
method - inside I just call method from service. Method inside service returns Observable to component. Here you can see piece of code:
public login(username: string, password: string): void{
this.authService.login(username, password) //this return Observable in real world
.catch(() => {
this.formErrors['general.error'] = true;
return Observable.throw('error! :<');
})
.subscribe(() => {
this.router.navigate(['/someRoute']);
});
}
As you can see it is very simple method (in real app it'll be a little more comlicated but is isn't important now) and now I'm trying to write a unit test (in Jasmine):
it('', () => {
authService.login.and.returnValue(Observable.throw('')); //authService is my mock
component.login('u', 'p');
expect(component.formErrors['general.error']).toBeTruthy();
});
But I get error becauseI thrown error from catch
section:
login.component login FAILED (error! :< thrown)
What I'm doing wrong?
P.S.
I've tried to add expect(component.login).toThrow();
but without success...
Upvotes: 1
Views: 8118
Reputation: 1427
Instead of calling component.login('u', 'p')
directly, try to have the test runner do it.
it('', () => {
authService.login.and.returnValue(Observable.throw('')); //authService is my mock
expect(component.login.bind(component, 'u', 'p')).toThrow(...);
expect(component.formErrors['general.error']).toBeTruthy();
});
Upvotes: 2