Angular中TypeScript函数测试未覆盖if-else分支,如何提升覆盖率?
问题原因及解决方案
核心问题
你用spyOn(component, 'toogleTag')创建了一个默认不执行原函数的间谍,导致toogleTag内部的if-else逻辑完全没被执行,自然不会产生分支覆盖。另外测试里只点击了一次按钮,却期望函数被调用2次,这也是逻辑错误。
修复步骤
让间谍执行原函数(或直接移除间谍)
如果需要验证函数被调用次数,用spyOn(component, 'toogleTag').and.callThrough(),这样间谍会在记录调用的同时执行原函数逻辑。如果不需要验证调用,直接删掉spyOn行即可,点击按钮会直接触发原函数。分别测试两个分支
要覆盖if和else分支,需要分别测试truthOrFalse从false变为true(进入if分支),以及从true变为false(进入else分支)的场景,建议拆成两个测试用例,或者在一个用例里连续点击两次并分别断言。明确初始状态
测试前要给truthOrFalse设置明确的初始值,避免依赖组件默认的不确定状态。
修改后的测试示例
测试if分支(从false到true)
it('devrait activer les champs quand toogleTag est appelé (false -> true)', fakeAsync(() => { // 初始化初始状态 component.truthOrFalse = false; // 如果需要验证调用,用callThrough()让间谍执行原函数 spyOn(component, 'toogleTag').and.callThrough(); const button = fixture.debugElement.nativeElement.querySelector('.slider'); button.click(); tick(); fixture.detectChanges(); // 触发变更检测,确保变量更新生效 expect(component.toogleTag).toHaveBeenCalled(); expect(component.truthOrFalse).toBeTruthy(); expect(component.showme).toBeTruthy(); expect(component.fraisAdministrationEditer).toBeTruthy(); expect(component.autreMentionEditer).toBeTruthy(); expect(component.tauxAdditionnelFADQEditer).toBeTruthy(); expect(component.sendInfoToggleService.editerReadOnly).toBeTruthy(); }));
测试else分支(从true到false)
it('devrait désactiver les champs quand toogleTag est appelé deux fois (true -> false)', fakeAsync(() => { // 初始化为true,模拟已点击过一次的状态 component.truthOrFalse = true; // 先同步初始状态到组件 fixture.detectChanges(); const button = fixture.debugElement.nativeElement.querySelector('.slider'); button.click(); tick(); fixture.detectChanges(); expect(component.truthOrFalse).toBeFalsy(); expect(component.showme).toBeFalsy(); expect(component.fraisAdministrationEditer).toBeFalsy(); expect(component.autreMentionEditer).toBeFalsy(); expect(component.tauxAdditionnelFADQEditer).toBeFalsy(); expect(component.sendInfoToggleService.editerReadOnly).toBeFalsy(); }));
额外提示
- 若不需要验证
toogleTag的调用次数,可直接移除spyOn,专注测试逻辑结果即可。 - 点击按钮后务必调用
fixture.detectChanges(),确保组件完成变更检测,变量更新后能被正确断言。
内容的提问来源于stack exchange,提问作者Futiliter
相关产品推荐
相关产品推荐

