使用jasmine进行subscribe方法的angular2测试

koh*_*hli 15 unit-testing karma-jasmine angular

我有一个规范代码来测试这样

 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();
    });
Run Code Online (Sandbox Code Playgroud)

和这样的实现代码

login() {

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

      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

它给出了错误:

this.auth.login(...).subscribe不是一个函数

为什么会发生这种错误?

Pau*_*tha 27

您需要使用subscribe方法返回一些内容,因为组件subscribe直接从中调用login.字符串没有.你可以只返回一个带有subscribe函数的对象,它应该可以工作

and.returnValue({ subscribe: () => {} });
Run Code Online (Sandbox Code Playgroud)

或者,如果你想通过一个真实的观察,你可以

and.returnValue(Observable.of('some value'));
Run Code Online (Sandbox Code Playgroud)

您可能需要导入 rxjs/add/observable/of


M.O*_*vio 7

在 rxjs v6 上,您应该使用of代替Observable.ofObservable.from例如

const loginService: any = {
    getUser: () => of(['Adam West']),
};
Run Code Online (Sandbox Code Playgroud)

和进口

import { of } from 'rxjs';
Run Code Online (Sandbox Code Playgroud)


hug*_*ook 5

更改您的 authService 上的“登录”方法的间谍以返回可观察的而不是值。您需要导入:

import 'rxjs/add/observable/from';
import {Observable} from 'rxjs/Observable';
Run Code Online (Sandbox Code Playgroud)

设置你的间谍:

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

呼叫登录:

fixture.componentInstance.login();
Run Code Online (Sandbox Code Playgroud)

断言:

expect(spy).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)