Angular 2 Http testing multiple connections
Asked Answered
C

2

12

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);
            });
        }));
});
Continuator answered 18/3, 2016 at 16:24 Comment(0)
M
17

I had an similar problem with an sequence of requests. But at first to your question.

Multiple Requests with different Urls

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'));

Sequence of Request with same Url

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.

Mesomorph answered 21/4, 2016 at 19:32 Comment(0)
M
6

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']
        })));
    }
  });
Merlon answered 18/3, 2016 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.