Search code examples
angularangular-test

Angular Component testing - query by Component


When testing the DOM representation of a @Component, you're able to query its nested elements via its fixture

fixture.debugElement.queryAll(By.css('.example'));

You can also filter by @Directive

fixture.debugElement.queryAll(By.directive(RouterLinkDirectiveStub));

Now, let's say you have an inner @Component NzButtonComponent used like this

<button nz-button>Example</button>

How can I precisely query for it? There is no By.component(...).


Solution

  • You can select by CSS attribute if you use the nativeElement instead of the debugElement:

    fixture.debugElement.nativeElement.querySelector<HTMLButtonElement>('[nz-button]');
    

    For multiple elements the querySelectorAll method can be used.