angular2 testing using jasmine for subscribe method

和自甴很熟 提交于 2019-11-29 06:25:12

问题


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?


回答1:


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




回答2:


On rxjs v6 you should use of instead of Observable.of or Observable.from e.g

const loginService: any = {
    getUser: () => of(['Adam West']),
};

and import

import { of } from 'rxjs';



回答3:


You need to mock the login function as follows:

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

you might find the observable.if function undefined, so you need to import the observable this way:

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



回答4:


Change your spy for the 'login' method on your authService to return an observable instead of a value. You'll need to import:

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

Setup your spy:

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

Call login:

fixture.componentInstance.login();

Assert:

expect(spy).toHaveBeenCalled();


来源:https://stackoverflow.com/questions/40080912/angular2-testing-using-jasmine-for-subscribe-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!