Access to a DebugElement of a nested component using built-in view encapsulation

I am testing the component as shown below.

@Component({
  selector: 'my-component',
  template: `
    <my-nested-component [state]="state"></my-nested-component>
  `,
  encapsulation: ViewEncapsulation.Native
})
export class MyComponent {}

When a module tests my component, I want to get a link to a nested component MyOtherComponent. If you my-componentdid not use encapsulation or used emulated encapsulation, I could use:

let fixture = TestBed.createComponent(MyComponent);
let nestedComponent = fixture.debugElement.query(By.directive(MyNestedComponent))

to get a link to the component.

But in this case, it querysimply requests light child elements of the DOM component (simulates the behavior querySelector), therefore, nestedComponent nullwhen using the built-in encapsulation of the view.

How should you get a reference to DebugElement(and therefore to a component instance) a nested component?

+4
1

, :

@Component({
  selector: 'my-nested-component',
  template: `
    <h1>Nested component - {{ state }}</h1> 
  `,
})
export class NesterComponent {
  @Input() state: number;
}

@Component({
  selector: 'my-app',
  template: `
    <my-nested-component [state]="state"></my-nested-component> 
  `,
  encapsulation: ViewEncapsulation.Native
})
export class TestComponent {
  state = 1;
}

, :

let fixture = TestBed.createComponent(TestComponent);
let component = fixture.componentInstance;

const shadowRoot: DocumentFragment = fixture.debugElement.nativeElement.shadowRoot;
const nestedComponentNativeElement = shadowRoot.querySelector('my-nested-component');

const nestedComponentDebugElement = <DebugElement>getDebugNode(nestedComponentNativeElement);

var nestedComponentInstance: NesterComponent = nestedComponentDebugElement.componentInstance;
// here can be your code

component.state = 2;
fixture.detectChanges();

de = nestedComponentDebugElement.query(By.css('h1'));

expect(de.nativeElement.textContent).toBe('Nested component - 2');

plunker

+3

Source: https://habr.com/ru/post/1662614/


All Articles