Pavel Schoffer
Pavel Schoffer

Reputation: 632

How to test modal content when using NgbModal service

I am using NgbModal to open the modal window described with <ng-template> directive. It seems to work quite well. But I can't figure out how to test the content of my modal.

I am new to this so feel free to point out any other issues you might see with my approach. I think the issue is that the <ng-template> content is not outputted before the modal is actually shown. So I tried to call click() on the toggle before, but that seems to not be enough.

For instance, there is a form in my content so my test could look like:

 it("toggle button should work", () => {
    const button = fixture.nativeElement.querySelector("button");
    expect(button).toBeTruthy();
    button.click();
    fixture.detectChanges();

    const formDe = fixture.debugElement.query(By.css("div"));
    expect(formDe).toBeTruthy();
  });

Here is my component:

import { Component } from "@angular/core";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";

@Component({
  selector: "app-login",
  template: `
    <ng-template #content>
      <div class="modal-body"></div>
    </ng-template>

    <button class="btn btn-lg btn-outline-primary" (click)="open(content)">
      Launch demo modal
    </button>
  `,
  styleUrls: ["./login.component.css"]
})
export class LoginComponent {
  constructor(private modalService: NgbModal) {}

  open(modal) {
    this.modalService.open(modal);
  }
}

I would like to be able to get a hold of the modal content in some way. currently, I am getting Error: Expected null to be truthy. On the div element.

Upvotes: 3

Views: 1337

Answers (1)

Pavel Schoffer
Pavel Schoffer

Reputation: 632

Thanks to the @JB Nizet link. I made it work using following:

  it("login button should work", () => {
    const button = fixture.nativeElement.querySelector("button");
    const contentBeforeClick = document.querySelector(".modal-content");
    expect(contentBeforeClick).toBeFalsy();

    button.click();

    const contentAfterClick = document.querySelector(".modal-content");
    expect(contentAfterClick).toBeTruthy();
  });

Upvotes: 2

Related Questions