简体   繁体   中英

How do I access the overridden child component's template in an Angular 2 unit test?

So if I have this

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

        });

 TestBed
        .overrideDirective(ChildComponent, MockChildComponent);

What are some ways I have to access the child/mock child component's template in the test?

The best way to override child components is simply to do,

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

    });

Declare MockChildComponent where ChildComponent would be. Only requirement is they should have the same selector in the template.

There is no need to declare the real ChildComponent along with the MockChildComponent, or to use TestBed.overrideDirective.

So this is how you access the MockChildComponent's template, or just the ChildComponent's template.

  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").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM