覆蓋子組件的最好方法是簡單地做,
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").
模板應該在父模板中呈現。所以只需從父nativeElement訪問它。除此之外,請提供一個更好的示例並解釋您需要訪問 –