任何人都可以帮助我在 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);
});
}));
});