[英]angular2 testing using jasmine for subscribe method
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 this.auth.login(...).subscribe 不是一个函数
Why does this error happen?为什么会发生这个错误?
You need to return something with a subscribe
method, as the component calls subscribe
directly from login
. 您需要使用subscribe
方法返回一些内容,因为组件直接从login
调用subscribe
。 A string does not. 字符串没有。 You could just return an object with a subscribe
function and it should work 你可以只返回一个带有subscribe
功能的对象,它应该可以工作
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
您可能需要导入rxjs/add/observable/of
On rxjs v6 you should use of
instead of Observable.of
or Observable.from
eg 在rxjs V6你应该使用of
,而不是Observable.of
或Observable.from
如
const loginService: any = {
getUser: () => of(['Adam West']),
};
and import 和进口
import { of } from 'rxjs';
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: 您可能会发现observable.if函数未定义,因此您需要以这种方式导入observable:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/of';
Change your spy for the 'login' method on your authService to return an observable instead of a value. 更改authService上'login'方法的间谍,以返回一个observable而不是一个值。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.