【发布时间】: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
不要复制大量的配置文件,这里是重现的步骤:
-
创建一个新项目
ng new testproj cd testproj -
创建一个组件
ng generate component mycomp 转到
./src/mycomp/mycomp.component.ts并注意其选择器(应为app-mycomp)-
编辑
./src/app/component.html并添加这一行:<app-mycomp></app-mycomp>app-mycomp是您在第 3 步中看到的选择器。 -
启动测试:
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,同样的问题。
【问题讨论】:
-
在为
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