如何为Angular组件中含if else分支的方法编写Jasmine单元测试
测试实现方案
测试核心逻辑为分别覆盖if、else两个分支,通过Jasmine提供的spyOn方法监听两个被调用函数的执行状态,即可验证逻辑正确性。
以下是可以直接写入component.spec.ts的测试代码:
describe('validationLoadListDownload', () => { it('当getGroupId为0时,调用loadListDownloadRequest', () => { // 给getGroupId赋值为0,触发if分支 component.getGroupId = 0; // 监听两个方法,用stub拦截真实执行,避免产生额外副作用 const downloadSpy = spyOn(component, 'loadListDownloadRequest').and.stub(); const groupDownloadSpy = spyOn(component, 'loadListDownloadRequestGroup').and.stub(); // 执行待测方法 component.validationLoadListDownload(); // 断言:if分支的方法被调用,else分支的方法未被调用 expect(downloadSpy).toHaveBeenCalled(); expect(groupDownloadSpy).not.toHaveBeenCalled(); }); it('当getGroupId不为0时,调用loadListDownloadRequestGroup', () => { // 给getGroupId赋值为非0值,触发else分支 component.getGroupId = 1; // 同样监听两个方法 const downloadSpy = spyOn(component, 'loadListDownloadRequest').and.stub(); const groupDownloadSpy = spyOn(component, 'loadListDownloadRequestGroup').and.stub(); // 执行待测方法 component.validationLoadListDownload(); // 断言:else分支的方法被调用,if分支的方法未被调用 expect(groupDownloadSpy).toHaveBeenCalled(); expect(downloadSpy).not.toHaveBeenCalled(); }); });
补充说明
- 如果
loadListDownloadRequest或者loadListDownloadRequestGroup本身需要同步执行原有逻辑,可以把.and.stub()去掉,或者替换成.and.callThrough(),会在监听的同时执行方法原有代码。 - 如果需要验证方法调用的参数,可以把
toHaveBeenCalled()换成toHaveBeenCalledWith(参数1, 参数2)的写法即可。
内容的提问来源于stack exchange,提问作者justTrustMe
相关产品推荐
相关产品推荐

