Observable.interval 的 Angular2 单元测试

Angular2 Unit test for Observable.interval

我有一项服务,每 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 测试出现错误:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

可以使用fakeAsync testing function and the 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
}));

您可以增加 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);