【问题标题】:Angular Testing of modal confirm dialog service Jest, Jasmine模态确认对话服务 Jest、Jasmine 的角度测试
【发布时间】:2021-09-09 09:13:48
【问题描述】:

我有以下问题:我使用了这个网站的代码

https://stackblitz.com/edit/angular-confirmation-dialog

在我的 Angular 项目中实现确认对话框。

现在我要测试服务:

confirmation-dialog.service.ts

import { Observable } from 'rxjs/Observable';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ConfirmationDialogComponent } from './confirmation-dialog.component';

@Injectable()
export class ConfirmationDialogService {

  constructor(private modalService: NgbModal) { }

  public confirm(
    title: string,
    message: string,
    btnOkText: string = 'OK',
    btnCancelText: string = 'Cancel',
    dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
    const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.message = message;
    modalRef.componentInstance.btnOkText = btnOkText;
    modalRef.componentInstance.btnCancelText = btnCancelText;

    return modalRef.result;
  }

}

我的调用方法是这样的:

this.confirmationDialogService.confirm(confirmHeadline, confirmString)
    .then((confirmed) => { do stuff});

我读到我可以使用 spyOn 方法来做到这一点,比如

spyOn(ConfirmationDialogService, 'confirm').and.callFake ...

但它不需要第二个参数。我是测试新手,所以我希望有人可以帮助我...谢谢!

【问题讨论】:

    标签: angular unit-testing jasmine modal-dialog karma-jasmine


    【解决方案1】:

    是的,您可以使用 spyOn。并且你可以通过使用 .withArgs(args) 来获取更多的(方法)第二个参数。 SpyOn 通常看起来像这样

    spyOn(obj, 'method');

    但是 .withArgs(args) 允许你添加更多:

    spyOn( modalService, 'open').withArgs(alertDialog, params, ...);
    你可以read more about spyOn here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      相关资源
      最近更新 更多