如何在角度单元测试中覆盖 try/catch 块

问题描述 投票:0回答:2
checkDefault(event) {
    try {
      this.defaultCard = event.checked;
      this.cardInfo.forEach((s) => {
        if (s.isDefault && event.checked) {
          const dialog = this.dialogService.dialogMethod(this.message.isDefaultAlertCard, this.dialogType.confirmation, true);
          dialog.afterClosed().subscribe((res) => {
            Eif (!res) {
              this.defaultCard = false;
            }
          });
        }
      });
    } catch (err) {
      this.errorObject.message = 'Error in checkDefault: ' + err && err.message ? err.message : null;
      this.sharedService.errorEmailNotification(this.storeId, this.errorObject);
      this.dialogService.dialogMethod(this.message.failedSave, this.dialogType.failure,
        true
      );
    }
  }

在这个函数中,我覆盖了 try 块,但没有覆盖 catch 块。如何覆盖它。

我的 try 块测试用例是

test('should create checkDefault', () => { 
    component.cardInfo = [{ isDefault: true, customer: "CustomerId", cardId: "cardId" }, { isDefault: false, customer: "CustomerId", cardId: "cardId" }];
    component.checkDefault({ checked: true });
    expect(component.checkDefault).toBeTruthy();

  });
angular unit-testing code-coverage catch-block
2个回答
0
投票

我找到了答案

component.checkDefault(null);

0
投票

监视

dialogMethod
并抛出错误,这将执行 catch 块。

spyOn(dialogService, 'dialogMethod').and.callFake(() => { throw new Error('test error message') })
© www.soinside.com 2019 - 2024. All rights reserved.