I have a spec code to test like this
it('login test', () => {
const fixture = TestBed.createComponent(component);
fixture.detectChanges();
let authService = fixture.debugElement.injector.get(Auth);
spyOn(authService, 'login').and.returnValue('');
const elements = fixture.nativeElement;
fixture.componentInstance.login();
expect(authService.login).toHaveBeenCalled();
});
and the implementation code like this
login() {
this.auth.login(this.username, this.password).subscribe(() => {
}
});
}
it gives error:
this.auth.login(...).subscribe is not a function
Why does this error happen?
You need to return something with a
subscribe
method, as the component callssubscribe
directly fromlogin
. A string does not. You could just return an object with asubscribe
function and it should workOr if you want to pass a real observable, you could
You might need to import
rxjs/add/observable/of
On rxjs v6 you should use
of
instead ofObservable.of
orObservable.from
e.gand import
You need to mock the login function as follows:
you might find the observable.if function undefined, so you need to import the observable this way:
Change your spy for the 'login' method on your authService to return an observable instead of a value. You'll need to import:
Setup your spy:
Call login:
Assert: