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);
});
}));
});
In fact, you need to mock only one response within the subscribed callback but the returned response can be different according to the request URL:
mockBackend.connections.subscribe(
(connection: MockConnection) => {
if (connection.request.url === 'file1.json') {
connection.mockRespond(new Response(
new ResponseOptions({
body: ['some message']
})));
} else {
connection.mockRespond(new Response(
new ResponseOptions({
body: ['some other message']
})));
}
});
I had an similar problem with an sequence of requests. But at first to your question.
var responses = {};
responses['data1.json'] = new Response(new ResponseOptions({body: 'data1'}));
responses['data2.json'] = new Response(new ResponseOptions({body: 'data2'}));
backend.connections.subscribe(connection => {
var response = responses[connection.request.url];
connection.mockRespond(response);
});
http.request('data2.json').subscribe(res => expect(res.text()).toBe('data2'));
http.request('data1.json').subscribe(res => expect(res.text()).toBe('data1'));
var responses = [];
responses.push(new Response(new ResponseOptions({body: '1st'})));
responses.push(new Response(new ResponseOptions({body: '2nd'})));
backend.connections.subscribe(connection => {
var response = responses.shift();
connection.mockRespond(response);
});
http.request('data.json').subscribe(res => expect(res.text()).toBe('1st'));
http.request('data.json').subscribe(res => expect(res.text()).toBe('2nd'));
My implementation is in javascript but should very easy to port to a typescript test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With