Angular Unit Test of a PRIME ng confirmation service
Asked Answered
C

5

10

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?

Ceria answered 6/11, 2017 at 8:15 Comment(0)
T
12

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();
})
Tammeratammi answered 18/4, 2018 at 1:48 Comment(1)
A // @ts-ignore right above the spyOn is what I needed to make this work.Brooklynese
S
7

on primeng > 7.1

spyOn(confirmationService, "confirm").and.callFake((confirmation: Confirmation) => confirmation.accept());
Suppressive answered 24/4, 2019 at 14:39 Comment(0)
K
3

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

spyOn(confirmationService, 'confirm').and.callFake((confirmation: Confirmation) => { return confirmation.accept(); });
Kreutzer answered 15/11, 2019 at 6:14 Comment(2)
Isnt that the same thing other answers have proposed?Phil
@Phil typescripts was complaining that confirmation.accept could be undefined, so I added a check in this style of confirmation and it workedRamiah
A
1

If anyone is using jest instead of Jasmine, the following code would do the trick

jest.spyOn(component['confirmationService'], 'confirm').mockImplementation(
    (options: any): any => {
        options.accept();
    },
);

Full example

it('should call resetConfirmationHandler if user confirms', () => {
    jest.spyOn(component['confirmationService'], 'confirm').mockImplementation(
        (options: any): any => {
            options.accept();
        },
    );

    const spy = jest.spyOn(component, 'resetConfirmationHandler');
    component.resetForm(new MouseEvent('click'));

    expect(spy).toHaveBeenCalled();
});
Allograph answered 7/5, 2024 at 17:50 Comment(0)
R
0

if you are facing Cannot invoke an object which is possibly 'undefined' from the above method the use this

spyOn(confirmationService, 'confirm').and.callFake((confirmation: Confirmation) => { return confirmation.accept?.(); });
Readability answered 15/6, 2023 at 11:46 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.