angular2 测试框架异步测试问题

angular2 testing framework async testing issue

我已经使用 angular-cli 创建了 angular2 项目和服务,并尝试测试我的服务。

但是API在异步函数中不会失败,尽管它应该会失败;此外,它只是忽略了那些异常。

/* tslint:disable:no-unused-variable */

import {
  beforeEach, beforeEachProviders, describe, xdescribe,
  expect, it, xit, async, inject, injectAsync
} from '@angular/core/testing';
import { SearchService } from './search.service';
import {provide} from '@angular/core';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {XHRBackend, Response, ResponseOptions, HTTP_PROVIDERS} from '@angular/http';

describe('Search Service', () => {
  let searchService: SearchService;
  let mockBackend: MockBackend;

  beforeEachProviders(() => [
    HTTP_PROVIDERS,
    MockBackend,
    provide(XHRBackend, { useClass: MockBackend }),
    SearchService
  ]);

  beforeEach(injectAsync([SearchService, MockBackend], (s, m) => {
    searchService = s;
    mockBackend = m;
  }));

  it('async test', () => {
    setTimeout(() => {
      expect(2).toBe(1);
    }, 3000);
  });

它只是忽略了那些最小的测试用例。

然后我阅读了一些文档并更新了我的代码如下。

it('async test with done', (done) => {
  setTimeout(() => {
    expect(1).toBe(1);
    done();
  }, 1000);
});

但这一次,本应通过的测试却失败了。报错如下。

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

我将默认超时值更改为更大的值,但没有效果。

injectAsync 将不起作用,请使用 async(在 rc2 后停止为我工作)

angular2 change log beta 16

injectAsync 现已弃用。相反,使用 async 函数来包装任何异步测试。 您还需要在 Karma 或其他测试配置中添加依赖项 'node_modules/zone.js/dist/async-test.js' 作为服务文件。

之前:

it('should wait for returned promises', injectAsync([FancyService], (service) => {
  return service.getAsyncValue().then((value) => { expect(value).toEqual('async value'); });
}));
it('should wait for returned promises', injectAsync([], () => {
  return somePromise.then(() => { expect(true).toEqual(true); });
}));

之后:

it('should wait for returned promises', async(inject([FancyService], (service) => {
  service.getAsyncValue().then((value) => { expect(value).toEqual('async value'); });
})));
// Note that if there is no injection, we no longer need `inject` OR `injectAsync`.
it('should wait for returned promises', async(() => {
  somePromise.then(() => { expect(true).toEqual(true); });
}));