使用茉莉花进行订阅方法进行angular2测试 [英] angular2 testing using jasmine for subscribe method
本文介绍了使用茉莉花进行订阅方法进行angular2测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个规范代码可以进行测试
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();
});
以及类似的实现代码
login() {
this.auth.login(this.username, this.password).subscribe(() => {
}
});
}
它给出了错误:
this.auth.login(...).subscribe不是函数
this.auth.login(...).subscribe is not a function
为什么会发生此错误?
推荐答案
您需要使用subscribe
方法返回某些内容,因为该组件直接从login
调用subscribe
.字符串没有.您可以使用subscribe
函数返回一个对象,它应该可以工作
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'));
您可能需要导入rxjs/add/observable/of
这篇关于使用茉莉花进行订阅方法进行angular2测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文