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

时间:2017-11-06 08:15:33

标签: angular unit-testing service primeng

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

//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),然后调用我的方法删除第一条记录。但什么也没发生。单元测试成功完成但没有数据被删除。

有什么想法吗?

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:0)

primng> 7.1

spyOn(confirmationService, "confirm").and.callFake((confirmation: Confirmation) => confirmation.accept());

答案 2 :(得分:-1)

您可以尝试以下代码。它适用于primeng 8.0.0

spyOn(confirmationService, 'confirm').and.callFake((confirmation: Confirmation) => { return confirmation.accept(); });