您如何知道单元测试时要导入哪些组件?

时间:2016-10-20 15:57:37

标签: unit-testing angular karma-runner

我正在使用Angular2(2.1.0)最终版本。

我在使用...

进行单元测试时通过AppModule导入所有组件
beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [AppModule],
      ...

然而,这使得测试运行缓慢。

我现在只列出我需要的组件如下......

  beforeEach(async(() => {
    // noinspection JSUnusedGlobalSymbols
    TestBed.configureTestingModule({
      imports: [BrowserModule, FormsModule, HttpModule], // modules
      declarations: [
        // pipes
        AttributeCheckPipe,
        // directives
        // DatePickerDirective,
        ...

但是,我有很多很多组件,我不确定要导入哪些组件。测试输出不告诉我需要导入哪些。它只是简单地通过(当我全部导入它们)或失败(如果我不是)但它并没有告诉我需要哪些。

错误是令人烦恼/无用的..

invokeTask@node_modules/zone.js/dist/zone.min.js:1:36996
onInvokeTask@node_modules/zone.js/dist/proxy.min.js:1:2190
invokeTask@node_modules/zone.js/dist/zone.min.js:1:36939
runTask@node_modules/zone.js/dist/zone.min.js:1:31466
a@node_modules/zone.js/dist/zone.min.js:1:17818
g@node_modules/core-js/client/shim.min.js:8:19058
node_modules/core-js/client/shim.min.js:8:19180
k@node_modules/core-js/client/shim.min.js:8:14294
l@node_modules/zone.js/dist/zone.min.js:1:18418
l@node_modules/zone.js/dist/zone.min.js:1:18175
node_modules/zone.js/dist/zone.min.js:1:18715

如何获得有关我无法导入哪些组件的反馈? THX

我正在使用Karma和PhantomJS。

我的Karma配置摘录是..

client: {
  captureConsole: true
},
logLevel: config.LOG_DEBUG

1 个答案:

答案 0 :(得分:5)

最后在这里取得了一些进展。我在 compileComponents()中添加了一个 catch 块,并记录了 e.message 并获得了一些有用的输出,这让我可以继续使用!

继承我的代码..

  beforeEach(async(() => {
    TestBed.configureTestingModule({

      imports: [FormsModule, HttpModule, routing], // modules

      declarations: [
        SaveSearchModalComponent
      ],
      providers: [
        ESQueryService,
        RESTQueryService,
      ]
    }).compileComponents()
      .then(() => {
        fix = TestBed.createComponent(SaveSearchModalComponent);
        instance = fix.componentInstance;
        injector = fix.debugElement.injector;
      }).catch((e) => {
      console.log(e.message);
      throw e;
    });
  }));

错误消息输出的摘录是......

  

'动态形式'不是一个已知的元素:   1.如果'动态形式'是一个Angular组件,然后验证它是否是此模块的一部分。   2.如果是动态形式'是一个Web组件,然后添加" CUSTOM_ELEMENTS_SCHEMA"到了' @ NgModule.schemas'这个组件   压制此消息。

令人惊讶的是,文档中没有任何内容(但我应该尽快猜到这一点!)

现在是什么......

哇,在完成上述操作后(修复了99%的问题),我遇到了另一个无用的错误信息......

组件e不是任何NgModule的一部分,或者模块尚未导入模块。

哪来自......

/node_modules/@angular/compiler/bundles/compiler.umd.js

所以按照...的建议。

Angular 2 Component is not part of any NgModule

我将此日志语句添加到 compiler.umd.js

// I ADDED THIS LOG STATEMENT
console.log('compType', String(compType));
// THIS LINE EXISTS ALREADY
throw new Error("Component " + stringify(compType) + " is not part of any NgModule or the module has not been imported into your module.");

这通常是罪魁祸首。但是,在这里我得到了虚假的输出......

  

日志:'功能e(e)   {__cov_m4LFTxiG42jWqZk7He0hiA.f [' 4'] ++; __ cov_m4LFTxiG42jWqZk7He0hiA.s [' 11'] ++; this.router = E,this.formErrors = {invalidCreds:1}; }'

提及this.router

所以我删除了路由导入并瞧!

但令人难以置信的是,这种痛苦是必要的。