我想测试以下返回 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;
});
}
我的规格文件:
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 方法。结果我的测试用例在没有被执行的情况下通过了。我错过了什么?
PS:MyService 目前没有在组件内部使用/调用。