繁体   English   中英

使用 jasmine 进行 angular2 测试订阅方法

[英]angular2 testing using jasmine for subscribe method

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

 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();
    });

和这样的实现代码

login() {

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

      }
    });
  }

它给出了错误:

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

为什么会发生这个错误?

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

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

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

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

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

在rxjs V6你应该使用of ,而不是Observable.ofObservable.from

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

和进口

import { of } from 'rxjs';

您需要模拟登录功能,如下所示:

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

您可能会发现observable.if函数未定义,因此您需要以这种方式导入observable:

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

更改authService上'login'方法的间谍,以返回一个observable而不是一个值。 你需要导入:

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

设置你的间谍:

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

致电登录:

fixture.componentInstance.login();

断言:

expect(spy).toHaveBeenCalled();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM