12

任何人都可以帮助我在 Angular 2 中测试 Http 请求。我有一个从两个 http 请求中获取流的服务。如何在测试中模拟这种行为?

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]
        }
    });
}

这是我的测试代码,我尝试使用连接数组,但收到一条错误消息,提示“失败:连接已解决”。我将连接的主体留空以避免暴露敏感数据。

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);
            });
        }));
});
4

2 回答 2

17

我在一系列请求中遇到了类似的问题。但首先是你的问题。

具有不同 URL 的多个请求

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

具有相同 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'));

我的实现是在 javascript 中,但应该很容易移植到 typescript 测试。

于 2016-04-21T19:32:28.770 回答
6

实际上,您只需要在订阅的回调中模拟一个响应,但返回的响应可以根据请求 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']
        })));
    }
  });
于 2016-03-18T16:36:14.923 回答