我正在使用 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
如何获得有关我未能导入哪些组件的反馈?谢谢
我正在使用 Karma 和 PhantomJS。
我的 Karma 配置摘录是..
client: {
captureConsole: true
},
logLevel: config.LOG_DEBUG
最佳答案
终于在这里取得了一些进展。我在 compileComponents() 中添加了一个 catch block 并记录了 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;
});
}));
错误消息输出的摘录是...
'dynamic-form' is not a known element: 1. If 'dynamic-form' is an Angular component, then verify that it is part of this module. 2. If 'dynamic-form' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
令人惊讶的是,文档中的任何地方都没有涵盖这一点(但我早该猜到这一点!)
现在……
哇,在完成上述操作(修复了 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.");
这通常可以识别罪魁祸首。然而,在这里我得到了虚假输出......
LOG: 'function e(e) {__cov_m4LFTxiG42jWqZk7He0hiA.f['4']++;__cov_m4LFTxiG42jWqZk7He0hiA.s['11']++;this.router=e,this.formErrors={invalidCreds:!1};}'
其中提到了 this.router
所以我删除了路由导入,瞧!
但令人难以置信的是,这种痛苦是必要的。
关于angular - 单元测试时如何知道要导入哪些组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40159207/