角度服务测试:找不到名称’asyncData’
发布时间:2020-12-17 18:00:39 所属栏目:安全 来源:网络整理
导读:所以我正在学习如何在Angular中测试服务,我试图在Angular文档中复制下面的例子. let httpClientSpy: { get: jasmine.Spy };let heroService: HeroService;beforeEach(() = { // TODO: spy on other methods too httpClientSpy = jasmine.createSpyObj('HttpC
|
所以我正在学习如何在Angular中测试服务,我试图在Angular文档中复制下面的例子.
let httpClientSpy: { get: jasmine.Spy };
let heroService: HeroService;
beforeEach(() => {
// TODO: spy on other methods too
httpClientSpy = jasmine.createSpyObj('HttpClient',['get']);
heroService = new HeroService(<any> httpClientSpy);
});
it('should return expected heroes (HttpClient called once)',() => {
const expectedHeroes: Hero[] =
[{ id: 1,name: 'A' },{ id: 2,name: 'B' }];
httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));
heroService.getHeroes().subscribe(
heroes => expect(heroes).toEqual(expectedHeroes,'expected heroes'),fail
);
expect(httpClientSpy.get.calls.count()).toBe(1,'one call');
});
我试图完全复制它,但它给了我以下错误:
有人可以帮我替换这个吗?或者告诉我在其他地方可能做错了什么? 以下是从Angular文档复制的测试文件: import {FindLocalsService} from './find-locals.service';
import {HttpClient,HttpClientModule} from '@angular/common/http';
let findLocalsService: FindLocalsService;
let httpClientSpy: { get: jasmine.Spy,post: jasmine.Spy };
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient',['get','post']);
findLocalsService = new FindLocalsService(<any> httpClientSpy,null);
});
it('should save location to server',function () {
const expectedData: any =
[{ id: 1,name: 'B' }];
httpClientSpy.post.and.returnValue(asyncData(expectedData));
findLocalsService.saveLocation('something').subscribe(
data => expect(data).toEqual(expectedData),fail
);
expect(httpClientSpy.post.calls.count()).toBe(1,'one call');
});
这是服务本身 @Injectable()
export class FindLocalsService {
constructor(private http: HttpClient,private authService: AuthenticationService){}
saveLocation(locationObj){
return this.http.post(url + '/findLocals/saveLocation',locationObj);
}
getThreeClosestPlayers() {
const userId = this.authService.currentUser().user._id;
console.log('entered 3 closest service',userId);
return this.http.get(url + '/findLocals/getThreeClosestPlayers/' + userId)
.pipe(
map((data: any) => data.obj),catchError(this.handleError)
)
}
}
解决方法
改变这一行:
httpClientSpy.get.and.returnValue(asyncData(expectedHeroes)); 使用()的Observable运算符 httpClientSpy.get.and.returnValue(of(expectedHeroes)); 这将返回一个可以订阅的observable并返回expectedHeroes.如果您使用的是Angular 6,则可以直接从rxjs导入: 从’rxjs’导入{of} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
