角2 MockBackend测试HTTP超时? [英] angular 2 MockBackend test http timeout?

查看:80
本文介绍了角2 MockBackend测试HTTP超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以测试服务的http超时行为?

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

即使将作业的超时设置为0,也没有使用"TIMEOUT"记录,我仍在使用MockBackend.

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

谢谢!

更新:最小示例,如果未注释超时,它将失败

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

推荐答案

这是因为subscribe方法的解析是异步的.您正在尝试同步测试.

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

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

  })
  expect(something)
})

在这里,他期望在订阅触发的任何异步任务之前同步发生.而且测试甚至在异步任务完成之前就同步完成(这就是为什么您永远看不到console.log的原因)

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)

您需要使用async并在订阅回调中执行期望操作

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)
  })
}))

或使用fakeAsync并通过调用tick

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

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

这篇关于角2 MockBackend测试HTTP超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆