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

P. *_*uhn 5 jasmine typescript ng-bootstrap angular

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

<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>
Run Code Online (Sandbox Code Playgroud)

打字稿:

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) {}
  //
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,可以动态实例化组件。因为是动态组件,需要在@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 );
}));
Run Code Online (Sandbox Code Playgroud)

通常,人们会:

fixture = TestBed.createComponent( Confirm4Component );
Run Code Online (Sandbox Code Playgroud)

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

P. *_*uhn 2

在 SEMJS 聚会上,我在本地被提示查看NgbModal Jasmine 测试。我的解决方案如下:

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);
}));
Run Code Online (Sandbox Code Playgroud)