I am trying to mock backend service for unit testing. Below is code service
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);
}
Below is my Jasmine Unit test case:
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));
});
}
})
I am getting error "TypeError: undefined is not an object (evaluating 'res[0].id')". Any idea what is wrong here?? Please help!!
找到的解决方案:我的回复正文格式不正确。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.