【问题标题】:PrimeNG and mocking confirmation servicePrimeNG 和模拟确认服务
【发布时间】:2020-09-23 07:36:41
【问题描述】:

我在尝试模拟 PrimeNG 确认服务时遇到问题,因此我可以测试接受功能。 我的组件上有以下方法

deleteRow(rowData: any): void{

      this.confirmationService.confirm({
        message: 'Are you sure that you want to perform this deletion?',
        accept: (): void => {
          this.messageService.add({
            severity: 'success',
            summary: `Deleted`,
            detail: `Deleted ${rowData.name}`
          });

          const index: number = this.areas.indexOf(rowData);
          this.areas.splice(index, 1);
        }
    });
  }

以及下面的测试

    const confirmationService: ConfirmationService = TestBed.get(ConfirmationService);

    const mockConfirm: any = spyOn(confirmationService, 'confirm').and.callFake((c: any) => {
      c.accept();
    });
    component.deleteRow({id: 'aaa'});

    expect(mockConfirm).toHaveBeenCalled();
    
  });

这是我的测试平台设置

  beforeEach(async(() => {
      TestBed.configureTestingModule({
        schemas: [NO_ERRORS_SCHEMA],
        declarations: [AreasListComponent],
        imports: [FormsModule,
          ReactiveFormsModule,
          ConfirmDialogModule,
          FieldsetModule,
          TableModule,
          ToastModule,
          DropdownModule,
          NoopAnimationsModule
        ],
        providers: [
          ConfirmationService,
          MessageService
        ]
      })
        .compileComponents();
    })
  );

模拟确认toHaveBeenCalled 失败,当我调试它时,服务上似乎没有模拟。

有人有什么想法吗?

问候

【问题讨论】:

  • 您能console.log 或调试假回调以查看它是否被调用?

标签: angular mocking primeng


【解决方案1】:

似乎问题在于confirm 方法在ConfirmationService 原型上,而不是在它自己的对象上。当您监视 confirm 方法时,您正在监视特定于实例的方法,因此它不起作用。

尝试以下代码,它应该可以工作:

const mockConfirm: any = spyOn(ConfirmationService.prototype, 'confirm').and.callFake((c: any) => {
  c.accept();
});

【讨论】:

  • 嗨,谢谢你为我指明了正确的方向。我不得不使用const mockConfirm: any = spyOn(confirmationService.__proto__, 'confirm').and.callFake((c: any) => { c.accept(); });
  • @pathe.kiran 你在看typescript文件,要了解ConfirmationService是如何定义的,你应该看看编译ts文件后生成的js文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2021-03-22
  • 2021-05-14
相关资源
最近更新 更多