2016-10-04 34 views
2

所以,如果我有這樣的如何在Angular 2單元測試中訪問重寫的子組件的模板?

TestBed.configureTestingModule({ 
      declarations: [ComponentToTest, ChildComponent, MockChildComponent], 

     }); 

TestBed 
     .overrideDirective(ChildComponent, MockChildComponent); 

有什麼辦法我要訪問子/模擬子組件的模板測試?

+0

模板應該在父模板中呈現。所以只需從父nativeElement訪問它。除此之外,請提供一個更好的示例並解釋您需要訪問 –

回答

2

覆蓋子組件的最好方法是簡單地做,

TestBed.configureTestingModule({ 
      declarations: [ParentComponentToTest, MockChildComponent], 

    }); 

聲明MockChildComponent其中ChildComponent會。只有要求是他們應該在模板中具有相同的選擇器。

沒有必要聲明真正的ChildComponent和MockChildComponent,或者使用TestBed.overrideDirective。

所以這就是你如何訪問MockChildComponent的模板,或者只是ChildComponent的模板。

let fixture: any = TestBed.createComponent(ParentComponentToTest); // calls ngOnInit 
    fixture.detectChanges(); 
    const MockChildCmpDOMEl: DebugElement[] = fixture.debugElement.queryAll(By.directive(MockChildCmp)); 

expect(MockChildCmpDOMEl[0].nativeElement.textContent).toBe("whatever is rendered by the first MockChildComponent"). 
+1

的具體方法,以便如果childMockcomponent有一個我想窺視的方法。我如何獲得對childMockcomponent的引用,所以我可以添加間諜? – Choco