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
在 rxjs v6 上,您应该使用of
代替Observable.of
或Observable.from
例如
const loginService: any = {
getUser: () => of(['Adam West']),
};
Run Code Online (Sandbox Code Playgroud)
和进口
import { of } from 'rxjs';
Run Code Online (Sandbox Code Playgroud)
更改您的 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)
归档时间: |
|
查看次数: |
30583 次 |
最近记录: |