angular cli:测试期间未知的选择器

angular cli : selectors unknown during tests

我正在学习如何使用 Angular 2 进行我的第一个测试,使用 angular-cli

当我创建一个新组件 MyComponent 时,然后将其选择器 app-mycomponent 添加到应用程序模板中,然后所有测试都失败并显示 app-mycomponent 未知。

这个问题只出现在测试中;如果我启动应用程序,那么一切都很好。

我的环境:

npm : 3.10.10
node : 6.9.5
angular-cli : 1.0.0-beta.32.3
jasmine-core: 2.5.2
protractor: 5.1.0

无需复制大量配置文件,这里是重现步骤:

  1. 创建一个新项目

    ng new testproj
    cd testproj
    
  2. 创建组件

    ng generate component mycomp
    
  3. 转到 ./src/mycomp/mycomp.component.ts 并记下它的选择器(应该是 app-mycomp

  4. 编辑 ./src/app/component.html 并添加此行:

    <app-mycomp></app-mycomp>
    

    其中 app-mycomp 是您在第 3 步中看到的选择器。

  5. 启动测试:

    ng test
    

然后这里报告失败:

Error: Template parse errors:
'app-mycomp' is not a known element:
1. If 'app-mycomp' is an Angular component, then verify that it is part of this module.
2. If 'app-mycomp' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
{{title}}</h1>
[ERROR ->]<app-mycomp></app-mycomp>"): AppComponent@3:0

这是一个错误,还是我做错了什么?我试过将 MyComponent 手动设置为 providerAppComponent,同样的问题。

感谢上面的评论,我弄清楚出了什么问题: AppComponent 测试模块不知道如何使用 MyComponent。我还不知道加载测试时幕后发生了什么,无论如何我们必须通过这种方式手动将所有组件依赖项指定到其测试中: 在 app.module.spec.ts 中,编辑调用 TestBed.configureTestingModule.

的 beforeEach 方法

之前:

beforeEach(() => {
TestBed.configureTestingModule({
  declarations: [ AppComponent ],
});

之后:

beforeEach(() => {
TestBed.configureTestingModule({
  declarations: [
    AppComponent , 
    MyComponent
  ],
});