angular 2 MockBackend测试http超时?

时间:2016-11-17 00:10:50

标签: angular karma-jasmine rxjs angular2-testing

有没有办法测试服务的http超时行为?

即使将作业超时设置为0,我也在使用MockBackend,没有记录“TIMEOUT”。

export class MyHttpService {
private sendGetRequest (job: HttpJob): Observable<any> {
    return this.http.get(job.getUrl(), this.options)
      .share()
      .timeout(job.getTimeout(), () => this.requestTimeout(job))
      .catch((err) => this.errorHandler(err, job));
  };

  private requestTimeout(job: HttpJob): Error {
    job.errorCode = ErrorCode.TIMEOUT;
    console.log('TIMEOUT');
    return new Error('timeout');
  }
...

测试(没有记录任何内容)

 it('should resolve to TIMEOUT', () => {
      job.timeout = 0;
      let response: any;
      service.sendRequest(job).subscribe(
        (res: Response) => {
          response = res.json();
          console.log('OK', res);
        },
        err => {
          response = err;
          console.log('ER', err);
        }
      );
      expect(job.errorCode).toEqual(ErrorCode.TIMEOUT);
    });

THX!

更新minimal example,如果取消注释超时,则会失败

1 个答案:

答案 0 :(得分:1)

这是因为subscribe方法的分辨率是异步的。您正试图同步测试。

it('..', () => {
  doSomthing().subscribe(() => {

  })
  expect(something)
})

在这里,他期望在订阅触发的任何异步任务之前同步发生。即使在异步任务完成之前,测试也会同步完成(这就是你从未见过console.log的原因)

您需要做的是使用async并在订阅回调中执行期望

import { async } from '@angular/core/testing'

it('..', async(() => {
  doSomthing().subscribe(() => {
    expect(something)
  })
}))

或者使用fakeAsync并通过调用tick

强制执行虚假的同步解析
import { fakeAsync, tick } from '@angular/core/testing'

it('..', fakeAsync(() => {
  doSomthing().subscribe(() => {
    // this is called when you tick
  })
  tick();
  expect(something);
}))
相关问题