angular - 使用 NgbModal 服务时如何测试模态内容

标签 angular bootstrap-modal

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

我是这方面的新手,所以请随时指出您在我的方法中可能遇到的任何其他问题。我认为问题在于 <ng-template>在实际显示模式之前不会输出内容。所以我之前尝试在切换按钮上调用 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);
  }
}

我希望能够以某种方式获取模态内容。目前,我得到 Error: Expected null to be truthy.关于div元素。

最佳答案

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

关于angular - 使用 NgbModal 服务时如何测试模态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471747/

相关文章:

jquery - Plotly 绘图无法在模态内自动缩放

jquery - 添加命名空间后 Bootstrap 模式不起作用

angular - 为什么无法修改从 ngRx 状态获取的项目副本?

angular - 升级到 Angular 8 后 d3.js 出错

javascript - 对象取消订阅错误: object unsubscribed

c# - 对预检请求的响应未通过访问控制检查(Angular2)

php - php-ajax 表单提交后不显示 Bootstrap 警报

javascript - NG- Bootstrap : open multiple modals in separate components from one click handler

javascript - 动态模态 Bootstrap

javascript - 如何将 FormControl 从模板传递给函数?