【问题标题】:How to test modal content when using NgbModal service使用 NgbModal 服务时如何测试模态内容
【发布时间】:2019-10-21 12:17:46
【问题描述】:

我正在使用 NgbModal 打开<ng-template> 指令描述的模态窗口。它似乎工作得很好。但我不知道如何测试我的模态内容。

我对此并不陌生,因此请随时指出您在我的方法中可能遇到的任何其他问题。我认为问题在于<ng-template> 内容在模态实际显示之前没有输出。所以我之前尝试在toggle上调用click(),但这似乎还不够。

例如,我的内容中有一个表单,因此我的测试可能如下所示:

 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();
  });

这是我的组件:

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);
  }
}

我希望能够以某种方式掌握模态内容。目前,我在div 元素上获得了Error: Expected null to be truthy.

【问题讨论】:

标签: angular bootstrap-modal


【解决方案1】:

感谢@JB Nizet 链接。我使用以下方法使其工作:

  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();
  });

【讨论】:

  • 太棒了!关键是在 html dom 树的最顶端选择 dom
猜你喜欢
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多