角CLI:测试过程中未知的选择器



我正在学习如何使用 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手动设置为provider中的AppComponent,同样的问题。

感谢上面的评论,我弄清楚了什么问题:AppComponent测试模块不知道如何使用MyComponent。我还不知道加载测试时发生了什么,无论如何,我们必须按照这种方式手动指定所有组件依赖项:在app.module.spec.ts中,编辑正在调用testbed.configuretestingmodule的each方法。

之前:

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

之后:

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

最新更新