2017-02-25 48 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 
    ], 
});