如何在 Jasmine 测试中与 ng-bootstrap 模态交互

How-to interact with ng-boostrap modal in Jasmine test

我正在使用 bootstrap 4 和 angular @ng-bootstrap 库 https://ng-bootstrap.github.io/#/components/modal。我写了一个简单的确认弹出模态消息,如下:

<div id='modalContainer' ngbModalContainer class="modal-content" aria-labelledby='ModalConfirmPopup'  aria-describedby='message'>
  <div class="modal-header">
    <h4 id='title' class="modal-title">Confirm</h4>
    <button id='dismissButton' type="button" class="close" aria-label="Close" (click)="activeModal.dismiss(false)">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p id='message'>{{ message }}</p>
  </div>
  <div class="modal-footer">
    <button id='okButton' type='button' class='btn btn-primary' (click)='activeModal.close(true)'>OK</button>
    <button id='cancelButton' type='button' class='btn btn-warning' (click)='activeModal.close(false)'>Cancel</button>
  </div>
</div>

打字稿:

import { Component, Input } from '@angular/core';
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
//
@Component({
  selector: 'app-confirm4',
  templateUrl: './confirm4.component.html'
})
export class Confirm4Component {
  //
  @Input() message;
  constructor(public activeModal: NgbActiveModal) {}
  //
}

有趣的是,动态实例化组件。 因为是动态组件,需要把组件添加到@NgModule entryComponents中,Jasmine测试也是如此。

我的问题是用 Jasmine 测试组件。我的“应该测试”的前 10 行包含托管组件中使用的基本代码,它希望确认一个操作。它实例化组件并处理响应和解雇。

it('should response with true when click the ok button...', async(() => {
  let response: boolean;
  const modalRef = modalService.open( Confirm4Component );
  modalRef.componentInstance.message = 'click ok button';
  modalRef.result.then((userResponse) => {
    console.log(`User's choice: ${userResponse}`)
    response = userResponse;
  }, (reason) => {
    console.log(`User's dismissed: ${reason}`)
    response = reason;
  });
  // now what?
  expect( response ).toEqual( true );
}));

通常,一个人会:

fixture = TestBed.createComponent( Confirm4Component );

但这会创建一个新实例。那么,如何单击“确定”按钮?

我在 SEMJS 聚会上被本地提示查看 NgbModal Jasmine tests。我的解决方法如下:

it('should response with true when click the ok button...', async(() => {
  console.log( 'Click ok button' );
  let response: boolean;
  modalRef.componentInstance.message = 'Click Ok button';
  modalRef.result.then((userResponse) => {
    this.response = userResponse;
    console.log(`Button clicked: ${userResponse}`)
  }, (reason) => {
    this.response = reason;
    console.log(`X clicked: ${reason}`)
  });
  let ok = (<HTMLElement>document.querySelector('#okButton'));
  ok.click();
  setTimeout( () => {
      expect( this.response ).toEqual( true );
    }, 10);
}));