Can anyone help me with testing Http requests in Angular 2. I have a service that gets a stream from two http requests. How do I mock this behaviour in my test?
loadData() {
return Observable.forkJoin(
this.http.get('file1.json').map((res:Response) => res.json()),
this.http.get('file2.json').map((res:Response) => res.json())
).map(data => {
return {
x: data[0],
y: data[1]
}
});
}
Here is my test code, I have tried to use an array of connections but I get an error message saying "Failed: Connection has already been resolved". I have left the body of the connections blank to avoid exposing sensitive data.
describe('Test Load Init Data', () => {
it('should load Menu Zones and Menu Sections',
inject([XHRBackend, AppInitService], (mockBackend, appInitService) => {
console.log('Lets do some testing');
//first we register a mock response
mockBackend.connections.subscribe(
(connection:MockConnection) => {
return [
connection.mockRespond(new Response(
new ResponseOptions({
body: []
})
)),
connection.mockRespond(new Response(
new ResponseOptions({
body: []
})
))
];
});
appInitService.loadData().subscribe(data => {
expect(data.x.length).toBeGreaterThan(0);
expect(data.y.length).toBeGreaterThan(0);
});
}));
});