angular 2 MockBackend test http timeout?

久未见 提交于 2019-12-11 06:42:46

问题


Is there a way to test http timeout behaviour of a service?

I'm using MockBackend even when setting job's timeout to 0 no logging of 'TIMEOUT' present.

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

test (nothing is logged)

 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!

update: minimal example, if timeout is uncommented, it will fail


回答1:


It's because the resolution of the subscribe method is asynchronous. You are trying to test synchronously.

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

  })
  expect(something)
})

Here, he expectation happens synchronously before any asynchronous tasks triggered by the subscription. And the test completes synchronously even before the asynchronous tasks are complete (that's why you never see the console.log)

What you need to do is either use async and do the expectation in the subscription callback

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

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

Or use fakeAsync and force a fake synchronous resolution by calling tick

import { fakeAsync, tick } from '@angular/core/testing'

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


来源:https://stackoverflow.com/questions/40644626/angular-2-mockbackend-test-http-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!