簡體   English   中英

PRIME ng 確認服務的 Angular 單元測試

[英]Angular Unit Test of a PRIME ng confirmation service

首先,我是角度單元測試的新手。 我想對以下從我的數據中刪除記錄的方法進行單元測試。 方法是:

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

  }

如您所見,我正在從 PRIME ng 調用確認服務,並打開一個對話框詢問用戶是否要刪除所選記錄。 (數據是我的記錄)。

這是我的單元測試:

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

所以我正在調用服務來加載我的數據 (dataService),然后調用我的方法來刪除第一條記錄。 但什么也沒有發生。 單元測試成功完成,但沒有刪除任何數據。

有什么想法嗎?

您可以使用 jasmine fake 覆蓋確認對話並調用接受函數,如下所示

spyOn(confirmationService, 'confirm').and.callFake((params: any) => {
      console.log(`fake calling accept`);
      params.accept();
})

在primeng > 7.1

spyOn(confirmationService, "confirm").and.callFake((confirmation: Confirmation) => confirmation.accept());

你可以試試下面的代碼。 它適用於primeng 8.0.0

spyOn(confirmationService, 'confirm').and.callFake((confirmation: Confirmation) => { return confirmation.accept(); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM