Unit testing 如何访问被重写的子组件';角2单元测试中的s模板?

Unit testing 如何访问被重写的子组件';角2单元测试中的s模板?,unit-testing,angular,Unit Testing,Angular,所以如果我有这个 TestBed.configureTestingModule({ declarations: [ComponentToTest, ChildComponent, MockChildComponent], }); TestBed .overrideDirective(ChildComponent, MockChildComponent); 在测试中访问子/模拟子组件的模板有哪些方法?覆盖子组件的最佳方法就是 Te

所以如果我有这个

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

        });

 TestBed
        .overrideDirective(ChildComponent, MockChildComponent);

在测试中访问子/模拟子组件的模板有哪些方法?

覆盖子组件的最佳方法就是

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

    });
在ChildComponent所在的位置声明MockChildComponent。唯一的要求是它们在模板中应该具有相同的选择器

  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").
不需要将真实的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访问它。除此之外,请提供一个更好的示例,并解释您需要访问什么。因此,如果childMockcomponent有一个我想要监视的方法,请提供一个更好的示例。如何获得对childMockcomponent的引用,以便添加spy?