Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 testing using jasmine for subscribe method

Tags:

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?

like image 530
kohli Avatar asked Oct 17 '16 07:10

kohli


People also ask

How do I check if a variable is defined in Jasmine?

currentVal = 0; describe("Different Methods of Expect Block",function () { it("Example of toBeDefined", function () { expect(currentVal). toBeDefined(); }); }); In the above code, toBeDefined() will check whether the variable currentVal is defined in the system or not.


1 Answers

You need to return something with a subscribe method, as the component calls subscribe directly from login. A string does not. You could just return an object with a subscribe function and it should work

and.returnValue({ subscribe: () => {} }); 

Or if you want to pass a real observable, you could

and.returnValue(Observable.of('some value')); 

You might need to import rxjs/add/observable/of

like image 77
Paul Samsotha Avatar answered Dec 10 '22 20:12

Paul Samsotha