Как сделать тестовый блок с жасмином для угловой 6 начальной загрузки 4 модальной - PullRequest
0 голосов
/ 30 января 2019

html

<ng-template #content let-modal>   
<h1>Modal content inside this ng-template #content </h1>  
</ng-template>

Кнопка открытия модели

<button  (click)="open(content)" > Open modal </button>

В файле ts

import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
constructor(  public modalService: NgbModal) { }

open(content) {  
          this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title', size: 'lg' }).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
          }, (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
          });
           }

Как выполнить тестовый пример с жасмином для этой функции open .

1 Ответ

0 голосов
/ 30 января 2019

Вот как я тестировал это в прошлом ...

Предполагая, что файл компонента TS выглядит следующим образом:

export class MyComponent {

  closeResult: string;

  constructor(private _modalService: NgbModal) {}

  public openModal(content): void {
    this._modalService.open(content, { size: 'lg' }).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
       this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    return  `with: ${reason}`;
  }
}

Вы можете использовать следующий тестовый класс, который будетпроверьте следующие сценарии:

  1. this._modalService.open вызывается с правильными параметрами
  2. Когда модальное окно закрыто, closeResult обновляется правильно
  3. Когда модальноеcloseResult обновляется корректно

Тестовый класс выглядит следующим образом:

import { TestBed, async, ComponentFixture, tick, fakeAsync } from '@angular/core/testing';
import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { MyComponent } from './my.component';

// Mock class for NgbModalRef
export class MockNgbModalRef {
  result: Promise<any> = new Promise((resolve, reject) => resolve('x'));
}

describe('MyComponent', () => {

  let fixtureUnderTest: ComponentFixture<MyComponent>;
  let componentUnderTest: MyComponent;
  let modalService: NgbModal;
  let mockModalRef: MockNgbModalRef = new MockNgbModalRef();

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MyComponent
      ],
      imports: [
        NgbModule.forRoot()
      ]
    }).compileComponents();

    fixtureUnderTest = TestBed.createComponent(MyComponent);
    componentUnderTest = fixtureUnderTest.componentInstance;
    modalService = TestBed.get(NgbModal);
  }));

  it('should open modal', () => {
    spyOn(modalService, 'open').and.returnValue(mockModalRef);
    componentUnderTest.openModal('<xxxx>');
    expect(modalService.open).toHaveBeenCalledWith('<xxxx>', { size: 'lg' });
  });

  // Needs to be async as modal result returned in a promise
  it('should update closeResult when modal closed', fakeAsync(() => {
    spyOn(modalService, 'open').and.returnValue(mockModalRef);

    componentUnderTest.openModal('<xxxx>');
    tick();
    expect(componentUnderTest.closeResult).toBe('Closed with: x');
  }));

  // Needs to be async as modal result returned in a promise
  it('should update closeResult when modal dismissed', fakeAsync(() => {
    spyOn(modalService, 'open').and.returnValue(mockModalRef);
    // Override the result returned from the modal so we can test what happens when the modal is dismissed
    mockModalRef.result = new Promise((resolve, reject) => reject('y'));

    componentUnderTest.openModal('<xxxx>');
    tick();
    expect(componentUnderTest.closeResult).toBe('Dismissed with: y');
  }));

});
...