首页 > 解决方案 > 使用 Mat 对话框在 Angular 中单元测试失败

问题描述

我们在 UI 中有一个按钮,单击该按钮在内部调用一个方法,该方法调用服务以执行某些操作,然后使用 mat 对话框显示返回消息。单元测试失败说“open() 方法不存在”。错误在代码行中被抛出 spyOn(component.dialog, 'open').and.callThrough();

在点击按钮后被调用:

public dosomething(){
    this.service
      .dosomething()
      .subscribe((result) => {
        this.showConfirmDialog(result);
        this.isDisabled = true;
      },
      error => {
        this.showErrorDialog();
      });
  }

以下是 showConfirmDialog() 的代码

private showConfirmDialog(result){
const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      messageHeader: heading,
      answerDescription: result,
      isShownAnswerDescription: true,
      isHidden: true,
    } as MessageData;

    const dialogRef = this.dialog.open(MessageDialogComponent, dialogConfig);
}

以下是单元测试:

it('should do something on click of button button', () => {
    spyOn(TestBed.inject(ConfigurationManagementService), 'dosomething')
      .and.returnValue(of('message'));
    spyOn(component.dialog, 'open').and.callThrough();

    component.isDisabled = false;
    component.dosomething();
    expect(component.dialog.open).toHaveBeenCalledWith(MessageDialogComponent);
  });

如果我遗漏任何东西,请告诉我...

提前致谢!!!

标签: angularangular-materialkarma-jasmineangular-uiangular-unit-test

解决方案


推荐阅读