2017-02-25 44 views
1

我正在学习如何使用angular-cli对Angular 2进行第一次测试。角度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>"): [email protected]:0 

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

+1

有你'SRC /应用程序/应用程序配置'TestBed'当添加'MyComponent'作为'declaration'。 component.spec.ts'?这应该是第5步;当您将组件添加到模板时,您还需要确保它在测试中可用。 – jonrsharpe

+0

@jonrsharpe:这是我正在计算的一部分,但角度cli似乎为我做了这一点,在我的spec文件中它使用beforEach两次它在哪里执行:beforeEach(async(()=> {TestBed.configureTestingModule({\ ttf0 {{0} {0}}}}}声明:[MyComponent] }) .compileComponents(); })); beforeEach(()=> { 夹具= TestBed.createComponent(MyComponent的); 成分= fixture.componentInstance; fixture.detectChanges(); }); – Giova

+1

这看起来像是针对MyComponent的测试,但该错误看起来像是针对AppComponent的测试。这是您需要将MyComponent添加到声明的测试 –

回答

0

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

前:

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

后:

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