Angular Unit Test of a PRIME ng confirmation service

只愿长相守 提交于 2021-01-27 06:03:37

问题


First of all i am newbie at angular unit testing. I want to unit test the following method that removes a record from my data. The method is:

//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: () => {       
      }
      });

  }

As you can see i am calling the confirmation service from PRIME ng and i open a dialog to ask the user if he wants to remove the selected record. (Data are my records).

This is my unit test:

 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();
});

So i am calling the service to load my data (dataService) and then calling my method to remove the first record. but nothing is happening. The unit test finishes succesfull but no data are removed.

Any thoughts?


回答1:


You can use a jasmine fake to override the confirm dialogue and call the accept function as follows

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



回答2:


on primeng > 7.1

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



回答3:


you can try the below code. It works on primeng 8.0.0

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


来源:https://stackoverflow.com/questions/47132412/angular-unit-test-of-a-prime-ng-confirmation-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!