Angular 6:如何编写mat-dialog的茉莉花测试规范

时间:2018-07-03 09:34:08

标签: angular karma-jasmine angular-unit-test

我试图编写一个mat-dialog的测试规范,但是我不能成功,问题在于它是由一个函数调用的。怎么做?谢谢你的帮助。 这是我的代码

 closeDialogCancelButton() {
    if (this.editFormData.dirty) {
      let dialogRef = this.dialogCancel.open(DialogCancel,
        {
          width: '250px',
          disableClose: true,
          data:
          {
            id: '1'
          }
        });
      dialogRef.afterClosed().subscribe(result => {
        if (result)
          this.dialog.close();
      });
    } else
      this.dialog.close();
  }

2 个答案:

答案 0 :(得分:1)

我通过嘲笑MatDialog解决了同样的问题。即:

import { of } from 'rxjs';

export class MatDialogMock {
    open() {
        return {
            afterClosed: () => of({ name: 'some object' })
        };
    }
}

然后在您的TestBed配置中提供此模拟。

providers: [{provide: MatDialog, useClass: MatDialogMock}]

答案 1 :(得分:0)

扩展Danilo的答案,并使用Angular 7,您可以类似于以下内容测试matDialog

要测试的方法是:

openExport() {
    const dialogRef = this.matDialog.open(ExportComponent, {
        data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
        if (result !== 'cancel') {
            this.export(result);
        }
    });
}

我的mat-dialog-close动作定义如下:

<div mat-dialog-actions>
    <button mat-button [mat-dialog-close]="'cancel'">Cancel</button>
    ...
</div>

您可以使用以下测试:

describe('openExport', () => {
  const testCases = [
    {
      returnValue: 'Successful output from dialog',
      isSuccess: true
    },
    {
      returnValue: 'cancel',
      isSuccess: false
    },
  ];

  testCases.forEach(testCase => {
    it(`should open the export matDialog and handle a ${testCase.isSuccess} output`, () => {
      const returnedVal = {
        afterClosed: () => of(testCase.returnValue)
      };
      spyOn(component, 'export');
      spyOn(component['matDialog'], 'open').and.returnValue(returnedVal);
      component.openExport();

      if (testCase.isSuccess) {
        expect(component.export).toHaveBeenCalled();
      } else {
        expect(component.export).not.toHaveBeenCalled();
      }

      expect(component['matDialog'].open).toHaveBeenCalled();
    });
  });
});

记住要为您的TestBed.configureTestingModule提供matDialogMAT_DIALOG_DATA

providers: [
  { provide: MatDialogRef, useValue: {} },
  { provide: MAT_DIALOG_DATA, useValue: {} }
]