如何在Angular 2单元测试中访问重写的子组件模板?

时间:2016-10-04 17:34:48

标签: unit-testing angular

所以,如果我有这个

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

        });

 TestBed
        .overrideDirective(ChildComponent, MockChildComponent);

我有什么方法可以在测试中访问子/ mock子组件的模板?

1 个答案:

答案 0 :(得分:2)

覆盖子组件的最佳方法就是这样做,

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

    });

声明ChildComponent所在的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").
相关问题