如何在Angular单元测试中覆盖checkDefault方法的catch代码块
如何编写测试用例覆盖checkDefault方法的catch块?
原方法实现
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) => { if (!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块测试用例
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(); });
覆盖catch块的测试方案
要覆盖catch块,核心是人为触发try块中的代码抛出异常,以下是两种可行的测试用例实现:
方案1:模拟依赖服务抛出错误
通过mock dialogService.dialogMethod 让其抛出错误,触发catch分支:
test('should handle error thrown by dialogService', () => { // 模拟dialogService.dialogMethod调用时抛出错误 spyOn(component.dialogService, 'dialogMethod').and.throwError('Mocked exception'); // 配置必要的组件属性,确保进入try块中的dialog调用分支 component.cardInfo = [{ isDefault: true }]; component.storeId = 'test-store-123'; component.errorObject = {}; // 调用目标方法 component.checkDefault({ checked: true }); // 验证catch块的逻辑是否正确执行 expect(component.errorObject.message).toBe('Mocked exception'); expect(component.sharedService.errorEmailNotification).toHaveBeenCalledWith('test-store-123', component.errorObject); expect(component.dialogService.dialogMethod).toHaveBeenCalledWith(component.message.failedSave, component.dialogType.failure, true); });
方案2:制造数组遍历异常
将cardInfo设置为非数组类型,调用forEach时会抛出类型错误:
test('should catch error when cardInfo is not an array', () => { // 将cardInfo设为null,触发forEach调用失败 component.cardInfo = null; component.storeId = 'test-store-123'; component.errorObject = {}; // 调用目标方法 component.checkDefault({ checked: true }); // 验证错误处理逻辑 expect(component.errorObject.message).toBeTruthy(); expect(component.sharedService.errorEmailNotification).toHaveBeenCalled(); expect(component.dialogService.dialogMethod).toHaveBeenCalledWith(component.message.failedSave, component.dialogType.failure, true); });
这两种测试用例都能确保代码进入catch分支,同时可以验证错误信息赋值、错误通知服务调用、失败对话框弹出等关键逻辑是否正常工作。
内容的提问来源于stack exchange,提问作者Naveen kumar
相关产品推荐
相关产品推荐

