1
votes

I have a function which executes some operations in the "accept" call of PrimeNg Confirmation service. I tried to write a Unit test case for it as following:

  fit('submit preview config', fakeAsync(() => {
   addValues();
   component.submitConfig();
   component.submitPreviewForm();
   fixture.detectChanges();
   const confirmationService = TestBed.get(ConfirmationService);
   tick(200);
   spyOn<any>(confirmationService, 'confirm').and.callFake((params: any) => {
     params.accept();
     httpMock.expectOne(baseUrl + '/api/project/addOrUpdate').flush(mockSubmitResponse);
     expect(component.successMsz).toBe(mockSubmitResponse.message);
   });
  flush();
}));

The problem is the execution never goes inside callFake. The test case passes but the operation never takes place. Any ideas are welcome.

This is the function I want to test:

submitPreviewForm() {

    const messageContent = `<strong>You have updated the following fields:</strong><br/>
    <span class="subText" style="font-size: 12px; color: blue;">&bull;${Array.from(this.updatedHighlightedFields).join('<br/> &bull;')}</span>
    <br/>
    <strong>This will clear JIRA data from DB. Are you sure you want to proceed?</strong>`;

    this.confirmationService.confirm({
        message: messageContent,
        accept: () => {
                    ...
                     }
    });
}

I am using V6 of PrimeNg. I saw the implementation on this Stack Overflow question: Angular Unit Test of a PRIME ng confirmation service

1

1 Answers

0
votes

Your order of operations seems to be a bit off, you need to spy before calling submitPreviewform.

Try this:

fit('submit preview config', fakeAsync(() => {
   const confirmationService = TestBed.get(ConfirmationService); // grab a handle of confirmationService
   spyOn<any>(confirmationService, 'confirm').and.callFake((params: any) => {
     params.accept();
     httpMock.expectOne(baseUrl + '/api/project/addOrUpdate').flush(mockSubmitResponse);
     expect(component.successMsz).toBe(mockSubmitResponse.message);
   }); // spy on confirmationService.confirm now
   addValues();
   component.submitConfig();
   component.submitPreviewForm();
   fixture.detectChanges();
   tick(200);
   flush();
}));