Angular2 jasmine testing for the subscription method

I have a specific testing code 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 implementation code like this

login() {

    this.auth.login(this.username, this.password).subscribe(() => {

      }
    });
  }

he gives an error:

this.auth.login (...). subscribe is not a function

Why is this error happening?

+4
source share
3 answers

You need to return something using the method subscribe, since the component calls subscribedirectly from login. The line does not work. You can simply return an object using a function subscribeand it should work

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

Or, if you want to convey a real observation, you could

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

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

+13
source

:

let loginService: any = {
    login(): Observable<any> {
        return Observable.of('you object');
    }
};

observable.if undefined, :

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/of';
+1

Change your spy for the login method in your authService to return the observed value instead of the value. You will need to import:

import 'rxjs/add/observable/from';
import {Observable} from 'rxjs/Observable';

Setting up your spy:

const loginResult = '';
const spy = spyOn(authService, 'login').and.callFake(() => {
    return Observable.from([loginResult]);
})

Login:

fixture.componentInstance.login();

Approve:

expect(spy).toHaveBeenCalled();
0
source

Source: https://habr.com/ru/post/1657960/


All Articles