1

我有一个函数在 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

4

1 回答 1

0

您的操作顺序似乎有点偏离,您需要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();
}));
于 2020-08-01T12:47:56.480 回答