确认服务PRIME的角度单元测试

问题描述 投票:4回答:2

首先,我是角度单元测试的新手。我想单元测试以下方法从我的数据中删除记录。方法是:

//Confirm Button for deletion


 confirm(name: string, id: any) {
      this.confirmationService.confirm({
          message: 'Are you sure you want to remove ' + name + ' from your list of Supporting Staff?',
          accept: () => {
             const index: number = this.data.indexOf(id);
              if (index !== -1) {
                this.data.splice(index,1);
                this.totalResults = this.data.length;
                this.updateVisibility();                
                this.alertMessage = { severity: 'success', summary: 'SUCCESSFUL REMOVAL', detail: 'You have successfully removed '+name+' from your Supporting Staff List.' };
                this.alertMessagesSrv.pushAlert(this.alertMessage);
               }   
          },
      reject: () => {       
      }
      });

  }

如您所见,我正在从PRIME ng调用确认服务,并打开一个对话框,询问用户是否要删除所选记录。 (数据是我的记录)。

这是我的单元测试:

 it('should remove a supporting staff from list', () => {
let fixture = TestBed.createComponent(SupportingStaffComponent);
let app = fixture.debugElement.componentInstance;
let dataService = fixture.debugElement.injector.get(ProvidersService);
let spy = spyOn(dataService,'getSupportingStaffList').and.callThrough(); 
fixture.detectChanges();
let confirmFunction = fixture.componentInstance.confirm(app.data[0].name,1);
let confirmService = fixture.debugElement.injector.get(ConfirmationService);
//fixture.nativeElement.querySelector('#btnYes').click();
let spyRemove = spyOn(confirmService,'accept').and.callThrough();

fixture.detectChanges();

console.log(app.data);
expect(app.data).toBeDefined();
});

所以我调用服务加载我的数据(dataService),然后调用我的方法删除第一条记录。但什么也没发生。单元测试成功完成但没有数据被删除。

有什么想法吗?

angular unit-testing service primeng
2个回答
5
投票

您可以使用jasmine fake来覆盖确认对话框并按如下方式调用accept函数

spyOn(confirmationService, 'confirm').and.callFake((params: any) => {
      console.log(`fake calling accept`);
      params.accept();
})

0
投票

是primeng> 7.1

spyOn(confirmationService, "confirm").and.callFake((confirmation: Confirmation) => confirmation.accept());
© www.soinside.com 2019 - 2024. All rights reserved.