8

I would like to test HTML elements within a ng-tamplate.

<ng-template>
  <button class="create"></button>
</ng-template>

Jasmine Test:

fixture = TestBed.createComponent(SomeComponent);
const htmlElement: HTMLElement = fixture.nativeElement;
// Does not work:
const p = htmlElement.querySelector('.create');

How can I get the html element inside the ng-template? If I place the button outside of the ng-template tag, it works. I think it has something to do with the shadow dom.

Versions: Jasmine 2.8.0; Angular 5.2.9

2
  • 2
    You have to create EmbeddedView. Commented May 2, 2018 at 7:42
  • 2
    Could you please clarify how to create an embeddedView? Commented May 2, 2018 at 9:01

1 Answer 1

2

I forgot to call fixture.detectChanges();. Only when you call this method, the component is rendered fully into the DOM (including shadow-DOM-elements). The following code works:

fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
const htmlElement: HTMLElement = fixture.nativeElement;
const p = htmlElement.querySelector('.create');

See https://angular.io/guide/testing#detectchanges for more details.

Sign up to request clarification or add additional context in comments.

4 Comments

we tried using fixture.detectChanges but could not get this to work. Is it that simple ? I was reading some other post where they are suggesting to create a wrapper component.
I have the same issue and this solution didn't work for me.
that did not work
it does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.