简体   繁体   English

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

[英]angular cli : selectors unknown during tests

I'm learning how to do my first tests with Angular 2, using angular-cli . 我正在学习如何使用angular-cli对Angular 2进行首次测试。

When I create a new component MyComponent , then add its selector app-mycomponent into the app template, then all tests fail and say that app-mycomponent is unknown. 当我创建一个新的组件MyComponent ,然后将其选择器app-mycomponent添加到app模板中,然后所有测试都失败并说app-mycomponent是未知的。

This problem occurs only in tests; 此问题仅在测试中发生; if I start the app then everything is fine. 如果我启动应用程序然后一切都很好。

My environment: 我的环境:

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

Rather than copying tons of config files, here are steps to reproduce: 这里是重现的步骤,而不是复制大量的配置文件:

  1. create a new project 创建一个新项目

     ng new testproj cd testproj 
  2. create a component 创建一个组件

     ng generate component mycomp 
  3. go to ./src/mycomp/mycomp.component.ts and note its selector (should be app-mycomp ) 转到./src/mycomp/mycomp.component.ts并记下它的选择器(应该是app-mycomp

  4. edit ./src/app/component.html and add this line: 编辑./src/app/component.html并添加以下行:

     <app-mycomp></app-mycomp> 

    where app-mycomp is the selector you saw in step 3. 其中app-mycomp是您在步骤3中看到的选择器。

  5. launch the tests: 启动测试:

     ng test 

then here the failures reported : 然后在这里报告失败:

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

Is it a bug, or have I done something wrong? 这是一个错误,还是我做错了什么? I've tried manually setting MyComponent as a provider into AppComponent , same problem. 我已经尝试将MyComponent手动设置为AppComponentprovider ,同样的问题。

Thanks to comments above I figured out what was going wrong: AppComponent test module didn't knew how to use MyComponent. 感谢上面的评论我弄清楚出了什么问题:AppComponent测试模块不知道如何使用MyComponent。 I don't know yet what is going on under the hood when the test is loaded, anyway we have to specify manually all component dependancies into its test by this way : In app.module.spec.ts, edit beforeEach method that is calling TestBed.configureTestingModule. 我还不知道在加载测试时会发生什么事情,无论如何我们必须通过这种方式手动将所有组件依赖指定到其测试中:在app.module.spec.ts中,编辑beforeEach方法调用TestBed.configureTestingModule。

before : 之前:

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

after : 之后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM