【问题标题】:Angular 6: How to write jasmine test spec for a mat-dialogAngular 6:如何为 mat-dialog 编写 jasmine 测试规范
【发布时间】:2018-12-11 13:37:36
【问题描述】:

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

【问题讨论】:

  • 能把所有的组件代码都加进去吗?
  • 我无法提供所有组件代码,但我认为这足以在 jasmine 中创建规范。
  • 我尝试了很多次,但是由于它指向其他组件而发生了一些错误。
  • this.dialogCancel 是什么服务?
  • 它只是 matdialog 的一个对象

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


【解决方案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 提供matDialogMAT_DIALOG_DATA

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

【讨论】:

    【解决方案2】:

    我通过模拟 MatDialog 解决了同样的问题。即:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      相关资源
      最近更新 更多