Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Unit Test of a PRIME ng confirmation service

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?

like image 958
apoellitsi Avatar asked Nov 06 '17 08:11

apoellitsi


3 Answers

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();
})
like image 133
blorkfish Avatar answered Oct 12 '22 20:10

blorkfish


on primeng > 7.1

spyOn(confirmationService, "confirm").and.callFake((confirmation: Confirmation) => confirmation.accept());
like image 5
Juri Avatar answered Oct 12 '22 20:10

Juri


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

spyOn(confirmationService, 'confirm').and.callFake((confirmation: Confirmation) => { return confirmation.accept(); });
like image 1
Shiljith MP Avatar answered Oct 12 '22 20:10

Shiljith MP