我想测试以下服务,该服务返回一个observable:
public getData(str:string) {
// return an observable
return this.http.get(‘calltoserviceapi’+str)
.map( (responseData) => {
return responseData.json().Abc;
})
.map((s: Array<any>) => {
let result:Array<AbcModel> = [];
if (s) {
s.forEach((s) => {
result.push(
new AbcModel(s.Val1,
s.Val2,
));
});
}
return result;
});
}
我的spec文件:
fdescribe ("my-service.spec.js", ()=> {
beforeEachProviders(() => [
MyService,
BaseRequestOptions,
MockBackend,
provide(Http, {
useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
}),
provide(XHRBackend, {useClass: MockBackend})
]);
fit('should get response',inject([XHRBackend, MyService], (mockBackend, service) => {
console.log("inside fit");
let response = "something returned from service";
let responseOptions = new ResponseOptions({ body: response });
mockBackend.connections.subscribe((connection: MockConnection) => {
connection.mockRespond(new Response(responseOptions));
});
service.getData('xyz').subscribe((a: MyModel[]) => {
expect(a.length).toBe(11); //this is NOT failing
expect(a).toContain(“something”);
}); //debugger not going inside subscribe
}));
在调试时,不执行subscribe方法。结果我的测试用例没有被执行就通过了。我错过了什么? P.S:MyService目前尚未在组件内使用/调用。
答案 0 :(得分:0)
我认为您需要添加async(...)
fit('should get response',async(inject([XHRBackend, MyService], (mockBackend, service) => {
使测试等到所有异步任务完成。否则,http.get()
任务将被安排,然后测试结束。
答案 1 :(得分:0)
最后我找到了解决方案。我做了两个改变:
imageView.setImageResource(R.drawable.your_icon_name);
这是代码:
async()