Angular单元测试中Jest toHaveBeenCalled未按预期生效求助
问题描述
我正在为Angular中的sendNotification方法编写单元测试,已覆盖else分支,但无法覆盖调用confirmPopup的if分支。
目标方法代码:
sendNotification() { this.validateTitle(); this.validateDescription(); if (!this.titleValid && !this.descriptionValid) { this.confirmPopup(); } else { this.openAlert(false, 'sent'); } }
当前Jest测试代码:
it('should call confirmPopup if titleValid and descriptionValid are true', () => { const confirmPopupSpy = jest.spyOn(component, 'confirmPopup'); component.titleValid = false; component.descriptionValid = false; component.sendNotification(); expect(confirmPopupSpy).toHaveBeenCalled(); });
解决建议
- 修正测试注释错误:测试注释描述和实际逻辑不符——逻辑中是
titleValid和descriptionValid都为false时才会调用confirmPopup,但注释写的是"为true时调用",先修正注释避免混淆。 - Mock验证方法避免变量被覆盖:调用
sendNotification时会先执行validateTitle()和validateDescription(),这两个方法大概率会重新赋值titleValid和descriptionValid,覆盖你手动设置的false值。需要用Jest mock这两个方法,阻止它们修改变量:it('should call confirmPopup when both titleValid and descriptionValid are false', () => { // Mock验证方法,防止覆盖手动设置的状态 jest.spyOn(component, 'validateTitle').mockImplementation(() => {}); jest.spyOn(component, 'validateDescription').mockImplementation(() => {}); const confirmPopupSpy = jest.spyOn(component, 'confirmPopup'); component.titleValid = false; component.descriptionValid = false; component.sendNotification(); expect(confirmPopupSpy).toHaveBeenCalled(); }); - 排查变量干扰因素:如果mock后还是不生效,检查是否有其他生命周期钩子或逻辑在修改
titleValid/descriptionValid,确保测试时组件状态是完全可控的。
内容的提问来源于stack exchange,提问作者Superthrone
相关产品推荐
相关产品推荐

