2016-11-11 53 views
5

我是相當新的角2。如何單位測試,如果角2組件包含另一個組件

我有一個組件,它的模板中又有一些其他組件。

如何編寫單元測試以檢查我的父組件是否包含其他組件。

提到一個示例或將我引導到資源將非常有幫助。

MyComponent.ts:

import { Component } from '@angular/core'; 
@Component({ 
selector: 'my-component', 
templateUrl: `<div> 
<other-component></other-component> 
</div>` 
}) 
export class MyComponent{ 

} 

OtherComponent.ts:

import { Component } from '@angular/core'; 
@Component({ 
selector: 'other-component', 
templateUrl: `<div> 
<h1>Other Component</h1> 
</div>` 
}) 
export class OtherComponent{ 

} 

回答

7

爲了測試組件,在編譯時,含有其他成分:

  • 注入你測試
  • 注入子組件的組件
  • 創建父組件
  • 發現變化
  • 使用querySelectorquerySelectorAll找到子組件

我通常只檢查元素是否存在,然後在spec中爲每個子組件進行進一步測試。

import { TestBed, async } from '@angular/core/testing'; 

import { AppComponent } from './app.component'; 
import { OtherComponent } from './other/other.component'; 

describe('AppComponent',() => { 
    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ 
     AppComponent, 
     OtherComponent 
     ], 
    }).compileComponents(); 
    })); 

    it('should create the app', async(() => { 
    const fixture = TestBed.createComponent(AppComponent); 
    const app = fixture.debugElement.componentInstance; 
    expect(app).toBeTruthy(); 
    })); 

    it('should have the other component', async(() => { 
    const fixture = TestBed.createComponent(AppComponent); 
    fixture.detectChanges(); 
    const compiled = fixture.debugElement.nativeElement; 
    expect(compiled.querySelector('app-other')).not.toBe(null); 
    })); 
}); 

檢查爲空與querySelector將確定您的組件是否存在。從querySelector MDN

如果找不到匹配項,則返回null;否則,它返回匹配元素的第一個 。


如果你想檢查是否有相同的子組件的多個實例,您可以使用querySelectorAll並檢查length屬性:

expect(compiled.querySelectorAll('app-other').length).toBeGreaterThan(4); 
7

在大多數情況下,你只是測試的外部組件。如果您只想讓角度忽略內部組件,最簡單的方法是將NO_ERRORS_SCHEMA添加到您的規範中。

進口{} NO_ERRORS_SCHEMA從 '@角/核心'

,然後在TestBed.configureTestingModule添加一行:

模式:[NO_ERRORS_SCHEMA]

測試將隨後忽視的事實您沒有在組件HTML中導入內部組件。

如果要使用外部組件測試內部組件,如果使用angular-cli,則會看到它們爲您自動生成的component.spec文件包含一個declarations數組,它是TestBed配置對象。因此,您所要做的就是導入文件並將該組件添加到聲明中。

所以你上面的例子:

import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 
import { By } from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 

import { MyComponent } from './my-component.component'; 
import { OtherComponent } from './other-component.component'; 

然後在你describe塊,你將有一個beforeEach

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

然後你的組件現在應該正確編譯沒有錯誤。如果您想查看整個設置,只需使用angular-cli生成一個新項目,並查看它生成的規格文檔。

+1

這並沒有真正回答他們有問題。他們希望確保模板中存在的組件不會從外部組件中測試內部組件或獨立測試組件。 –

相關問題