【问题标题】:angular cli : selectors unknown during testsangular cli:测试期间选择器未知
【发布时间】:2017-02-25 13:32:28
【问题描述】:

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

当我创建一个新组件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,同样的问题。

【问题讨论】:

  • 在为src/app/app.component.spec.ts 配置TestBed 时,您是否将MyComponent 添加为declaration?那应该是第5步;当您将组件添加到模板时,您还需要确保它在测试中可用。
  • @jonrsharpe :这是我正在计算的部分,但角度 cli 似乎为我做这件事,在我的规范文件中,它使用 beforEach 两次:beforeEach(async(() => { TestBed.configureTestingModule({ 声明:[ MyComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MyComponent); component = fixture.componentInstance; fixture.detectChanges(); });
  • 这看起来像是针对 MyComponent 的测试,但错误看起来像是针对 AppComponent 的测试。那就是您需要将 MyComponent 添加到声明中的测试
  • AppComponent 使用了 MyComponent,所以需要在测试中添加到声明中。使用 TestBed,您可以从头开始配置模块。因此,组件工作需要什么,您需要将其添加到测试台
  • edit 提问。 CLI 可以将新组件添加到模块中(因此在您提供它时它可以工作)但不会将它添加到应用程序组件的测试中(因为它不知道您计划在哪里使用它 - 您在创建之后添加它。它很有用,它不是魔法。

标签: angular jasmine components selector angular-cli


【解决方案1】:

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

之前:

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

之后:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 2018-10-19
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多