Obularable.interval的Angular2单元测试

时间:2017-11-29 13:18:49

标签: angular unit-testing karma-runner

我有一个服务,每500毫秒轮询来自服务器的数据。为此,我使用了Observable.interval()

以下是我的代码。我想为这项服务编写单元测试

service.ts:

pollData() {
       Observable.interval(500).mergeMap(() =>
       this._http
      .get(url, { headers: headers })
      .map((resp: Response) => resp.json())
});

Service.spec.ts:

it('should get the response correctly', async(inject(
  [SomeService, MockBackend], (service, mockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
      connection.mockRespond(new Response(new ResponseOptions({ body: 
      mockResponse})));
   });
    const result = service.pollData();

    result.subscribe(response => {
       expect(response).toEqual(mockResponse);
    });
  }
)));

在运行ng测试时出错:

  

错误:超时 - 超时内未调用异步回调   由jasmine.DEFAULT_TIMEOUT_INTERVAL指定。

2 个答案:

答案 0 :(得分:4)

您可以使用fakeAsync测试功能和tick功能来模拟间隔。以下是演示此行为的示例方法和相关测试。

组件方法

public testMe() {
  return Observable.interval(500).mergeMap((period: number) => {
    return Observable.of(period);
  });
}

测试方法

it('should test method with interval', fakeAsync(() => {
  const obs = component.testMe();
  let currentVal = undefined;
  const sub = obs.subscribe((v) => {
    currentVal = v;
  });
  tick(500);
  expect(currentVal).toEqual(0);
  tick(500);
  expect(currentVal).toEqual(1);
  tick(500);
  expect(currentVal).toEqual(2);
  /* ... */
  sub.unsubscribe(); // must unsubscribe or Observable will keep emitting resulting in an error
}));

答案 1 :(得分:0)

您可以增加jasmine的默认超时间隔。假设您的测试需要30秒,您可以执行以下操作:

it('should get the response correctly', async(inject(
  [SomeService, MockBackend], (service, mockBackend) => {
    mockBackend.connections.subscribe((connection: MockConnection) => {
      connection.mockRespond(new Response(new ResponseOptions({ body: 
      mockResponse})));
   });
    const result = service.pollData();

    result.subscribe(response => {
       expect(response).toEqual(mockResponse);
    });
  }
   // increasing the jasmine.DEFAULT_TIMEOUT_INTERVAL to 30s.
)), 30000);
相关问题