Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Http testing multiple connections

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);
            });
        }));
});
like image 669
Jusef Avatar asked Mar 18 '16 16:03

Jusef


2 Answers

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']
        })));
    }
  });
like image 43
Thierry Templier Avatar answered Oct 04 '22 19:10

Thierry Templier


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.

like image 148
David Boho Avatar answered Oct 04 '22 18:10

David Boho