将基本测试提供程序设置为多个单元测试时出错

时间:2016-05-24 16:43:02

标签: unit-testing angular karma-runner

我使用Angular2 RC1,我有几个关于不同组件的单元测试,具有以下结构:

import {provide} from '@angular/core';
import {
  TestComponentBuilder
} from '@angular/compiler/testing';

import {
  beforeEach,
  ddescribe,
  xdescribe,
  describe,
  expect,
  iit,
  inject,
  injectAsync,
  async,
  beforeEachProviders,
  setBaseTestProviders,
  it,
  xit
} from '@angular/core/testing';

import {
  TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
  TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS
} from '@angular/platform-browser-dynamic/testing/browser';

describe('Test component 1', () => {
  setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
    TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);

  it('should something',
    async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
      var updateService = new UpdateService();

      tcb.overrideProviders(ShapeCircleLayerComponent, [
        provide(UpdateService, { useValue: updateService })
      ])
      .createAsync(Component1).then((componentFixture) => {
        (...)
      });
    });
  });
});

如果单独运行每个测试都有效,但是当我在Karma中同时运行它们时,我收到以下错误:

  

Chrome 50.0.2661(Linux 0.0.0)对形状圆层的测试遇到声明异常FAILED          错误:无法设置/home/(...)/my-project提供程序,因为它已被调用           在新的BaseException(/home/(...)/my-project/node_modules/@angular/core/src/facade/exceptions.js:17:23)           at Object.setBaseTestProviders(/home/(...)/my-project/node_modules/@angular/core/testing/test_injector.js:74:15)   ```

似乎有几个测试设置了基础测试提供程序(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERSTEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS}无法同时执行。

有没有人有这个问题?非常感谢!

1 个答案:

答案 0 :(得分:1)

正如@teleaziz建议的那样,你应该只做一次。因此需要将此类处理移动到karma-test-shim.js文件中。这是一个示例:

System.import('@angular/platform-browser/src/browser/browser_adapter')
  .then(function(browser_adapter) { browser_adapter.BrowserDomAdapter.makeCurrent(); })
  .then(function() {
    return Promise.all([
      System.import('@angular/core/testing'),
      System.import('@angular/platform-browser-dynamic/testing/browser')
    ]);
  })
  .then(function(modules) {
    var testing = modules[0];
    var testingBrowser = modules[1];

    testing.setBaseTestProviders(
       testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
       testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);
    })
  .then(function() { return Promise.all(resolveTestFiles()); })
  .then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); });