PrimeNg 确认服务的 Jasmine 测试用例不起作用

Jasmine test case for PrimeNg Confirmation Service not working

我有一个函数可以在 PrimeNg 确认服务的“接受”调用中执行一些操作。我尝试为它编写一个单元测试用例,如下所示:

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

问题是执行永远不会进入 callFake 内部。测试用例通过但操作从未发生。欢迎任何想法。

这是我要测试的功能:

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

我正在使用 PrimeNg 的 V6。 我看到了这个 Stack Overflow 问题的实现: Angular Unit Test of a PRIME ng confirmation service

你的操作顺序好像有点不对,需要先spy再调用submitPreviewform

试试这个:

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