Angular中如何测试isPerson getter属性?我的尝试未成功
正确测试Angular中getter属性的方法
首先先明确你原测试代码的几个问题:
- 实例化的
Person类并非包含isPersongetter的类,你的getter依赖this.persons和this.personId,但测试里没有初始化这些依赖属性 - 测试中spy了
isPerson却断言fullName,两者完全不相关 - 没有针对getter的实际业务逻辑做验证
以下是两种正确的测试方式:
方式一:直接测试getter的业务逻辑(推荐)
这种方式直接验证getter的实际返回值是否符合预期,最能体现业务逻辑的正确性。假设你的getter属于某个组件/服务(比如PersonComponent):
组件/服务代码示例
export class PersonComponent { persons: string[]; // 根据实际类型调整,比如是Person对象数组则改为Person[] personId: string; // 对应persons数组中元素的类型 get isPerson() { return this.persons.some((person) => person === this.personId); } }
测试代码
// 测试存在匹配的情况 it('should return true when personId exists in persons array', () => { const component = new PersonComponent(); // 初始化依赖属性 component.persons = ['user1', 'user2', 'user3']; component.personId = 'user2'; expect(component.isPerson).toBe(true); }); // 测试不存在匹配的情况 it('should return false when personId does not exist in persons array', () => { const component = new PersonComponent(); component.persons = ['user1', 'user2']; component.personId = 'user3'; expect(component.isPerson).toBe(false); }); // 测试空数组的边界情况 it('should return false when persons array is empty', () => { const component = new PersonComponent(); component.persons = []; component.personId = 'user1'; expect(component.isPerson).toBe(false); });
方式二:Spy getter(用于测试依赖它的其他逻辑)
如果你的其他方法依赖isPerson的返回值,需要通过spy来模拟getter的返回结果,此时要注意指定get特性:
依赖getter的方法示例
export class PersonComponent { // ... 原有属性和getter handleAction() { return this.isPerson ? '操作允许' : '操作拒绝'; } }
测试代码
it('should return "操作允许" when isPerson is true', () => { const component = new PersonComponent(); // spy getter,第三个参数指定为'get'表示监听getter const isPersonSpy = spyOnProperty(component, 'isPerson', 'get').and.returnValue(true); const result = component.handleAction(); expect(result).toBe('操作允许'); expect(isPersonSpy).toHaveBeenCalled(); }); it('should return "操作拒绝" when isPerson is false', () => { const component = new PersonComponent(); spyOnProperty(component, 'isPerson', 'get').and.returnValue(false); const result = component.handleAction(); expect(result).toBe('操作拒绝'); });
内容的提问来源于stack exchange,提问作者André Castro
相关产品推荐
相关产品推荐

