我正在尝试模拟单元测试的后端服务。以下是代码服务
getFreightById(id: number): Promise < Freight[] > {
let searchParams = new URLSearchParams();
searchParams.set('id', id.toString());
return this.http.get("app/freight/getById", {
search: searchParams
})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
以下是我的Jasmine Unit测试案例:
describe('FreightService', () => {
beforeEachProviders(() => [
BaseRequestOptions,
MockBackend,
FreightService,
provide(Http, {
useFactory: (backend: ConnectionBackend,
defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}, deps: [MockBackend, BaseRequestOptions]}),
]);
describe('getFreightById', () => {
it('retrieves using the Freight ID',
inject([FreightService, MockBackend], fakeAsync((freightService, backend) => {
var res;
expectURL(backend, 'app/freight/getById?id=4');
freightService.getFreightById(4).then((_res) => {
res = _res;
})
tick();
expect(res[0].id).toBe(4);
}))
);
});
// sets up an expectation that the correct URL will being requested
function expectURL(backend: MockBackend, url: string) {
backend.connections.subscribe(c => {
expect(c.request.url).toBe(url);
let response = new ResponseOptions({
body: '[{"id": "4"}]' });
c.mockRespond(new Response(response));
});
}
})
我收到错误&#34; TypeError:undefined不是对象(评估&#39; res [0] .id&#39;)&#34;。知道这里有什么问题吗?请帮忙!!