angular2测试框架异步测试问题

时间:2016-06-29 00:17:52

标签: unit-testing asynchronous angular karma-jasmine

我创建了角度2项目和带有angular-cli的服务,并尝试测试我的服务。

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

/* 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指定的超时时间内未调用异步回调。

我将默认超时值更改为更大的值但不起作用。

1 个答案:

答案 0 :(得分:6)

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