2017-02-24 57 views
1

我有一個組件測試如下:如何在Angular2中測試transclusion(ng-content)?

import {Component, OnInit, Input} from "@angular/core"; 

@Component({ 
    selector: 'column', 
    template: '<ng-content></ng-content>', 
    host: { 
     '[class]': '"col col-" + width' 
    } 
}) 
export class ColumnComponent implements OnInit { 

    @Input() public width: number; 

    ngOnInit() { 
     if (!this.width || this.width > 12 || this.width < 1) { 
      this.width = 12; 
     } 
    } 

} 

我不能夠找到一個優雅的方式來測試<ng-content>。檢查了文件,但無法找到一個好方法。

我認爲有一個測試包裝組件將有所幫助。但comp不使用TestContainerComponent的一個,這樣的測試失敗

@Component({ 
     selector: 'test-container', 
     template: `<column width="12">Hello</column>` 
    }) 
    export class TestContainerComponent { 
    } 

    fdescribe(`Column`,() => { 
     let comp: ColumnComponent; 
     let fixture: ComponentFixture<ColumnComponent>; 

     let testContainerComp: TestContainerComponent; 
     let testContainerFixture: ComponentFixture<TestContainerComponent>; 
     let testContainerDe: DebugElement; 
     let testContainerEl: HTMLElement; 

     beforeEach(async(() => { 
      TestBed.configureTestingModule({ 
       declarations: [ColumnComponent, TestContainerComponent] 
      }).compileComponents(); 
     })); 

     beforeEach(() => { 
      fixture = TestBed.createComponent(ColumnComponent); 
      testContainerFixture = TestBed.createComponent(TestContainerComponent); 
      comp = fixture.componentInstance; 

      testContainerComp = testContainerFixture.componentInstance; 
      testContainerDe = testContainerFixture.debugElement.query(By.css('column')); 
      testContainerEl = testContainerDe.nativeElement.; 

     }); 


     it(`Should have a width class as 'col-...' if width attribute set`,() => { 
      comp.width = 6; 
      testContainerFixture.detectChanges(); 
     expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy(); 
     }); 

    }); 

我想我需要一種方式來獲得從TestContainerComponentColumnComponent組件。

+1

使用'ViewChild'來保存對'ColumnComponent'的引用怎麼樣? – yurzui

回答

2

我認爲你可以做到這一點,而不使用的包裝,因爲沒有辦法通過打電話來獲取主機元素:

fixture.elementRef.nativeElement; 

所以這裏是可能的測試:

fdescribe(`Column`,() => { 
    let comp: ColumnComponent; 
    let fixture: ComponentFixture<ColumnComponent>; 

    let testContainerDe: DebugElement; 
    let testContainerEl: HTMLElement; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ColumnComponent] 
    }).compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(ColumnComponent); 
    comp = fixture.componentInstance; 
    testContainerEl = fixture.elementRef.nativeElement; 
    }); 

    it(`Should have a width class as 'col-...' if width attribute set`,() => { 
    comp.width = 6; 
    fixture.detectChanges(); 
    expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy(); 
    }); 
}); 

Plunker Example

+0

我不知道'fixture'有'elementRef'。謝謝 :) – semirturgay