Angular TypeScript中如何编写Helper类unsubscribeSubscriptions方法的单元测试
单元测试实现方案
测试unsubscribeSubscriptions方法的核心逻辑是验证有效订阅实例的unsubscribe方法被正确调用,空值不会触发报错,你可以借助测试框架的间谍(Spy)能力实现,以下是完整测试代码(默认适配Angular自带的Jasmine测试框架):
import { Helper } from './helper.ts'; // 替换为你实际的Helper类导入路径 import { Subscription } from 'rxjs'; describe('Helper', () => { // 你原有的isNullOrEmpty测试可以保留在这里 describe('unsubscribeSubscriptions', () => { it('should call unsubscribe for all valid subscriptions in the array', () => { // 创建两个模拟订阅实例,监听unsubscribe方法 const mockSub1 = new Subscription(); const mockSub2 = new Subscription(); spyOn(mockSub1, 'unsubscribe'); spyOn(mockSub2, 'unsubscribe'); // 调用待测试方法 Helper.unsubscribeSubscriptions([mockSub1, mockSub2]); // 验证两个订阅的unsubscribe都被调用了1次 expect(mockSub1.unsubscribe).toHaveBeenCalledTimes(1); expect(mockSub2.unsubscribe).toHaveBeenCalledTimes(1); }); it('should skip null/undefined values and not throw error', () => { const validSub = new Subscription(); spyOn(validSub, 'unsubscribe'); // 数组混合传入空值和有效订阅 Helper.unsubscribeSubscriptions([null, validSub, undefined, null]); // 验证有效订阅仍被正常取消,方法没有抛出错误 expect(validSub.unsubscribe).toHaveBeenCalledTimes(1); }); it('should not throw error when input is empty array', () => { // 验证空数组传入时不会报错 expect(() => Helper.unsubscribeSubscriptions([])).not.toThrow(); }); }); });
测试逻辑说明
- 我们通过
spyOn监听订阅实例的unsubscribe方法,不需要真实发起订阅请求,只需要验证方法调用行为符合预期即可 - 覆盖了三种核心场景:全有效订阅、混合空值、空数组输入,覆盖原方法的所有逻辑分支
- 如果你使用Jest作为测试框架,只需要把Spy相关的API替换为Jest对应的写法即可,整体测试逻辑完全一致
内容的提问来源于stack exchange,提问作者Miomir Dancevic
相关产品推荐
相关产品推荐

