4

我试图为 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();
  }
4

2 回答 2

3

我通过 mocking 解决了同样的问题MatDialog。IE:

import { of } from 'rxjs';

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

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

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

于 2018-10-09T05:03:12.313 回答
1

扩展 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提供matDialogand MAT_DIALOG_DATA

providers: [
  { provide: MatDialogRef, useValue: {} },
  { provide: MAT_DIALOG_DATA, useValue: {} }
]
于 2019-02-11T12:21:21.157 回答