如何用Jest测试空对象场景以实现100%代码覆盖率?
解决Jest代码覆盖率未覆盖
|| ''分支的问题 首先修正你的解析函数中的语法错误(否则测试无法正常运行):
parsedResponse = (res: string): unknown => { const Data = res.split('^^^'); const Length = Data.length; if (Length > 1) { const firstIndexArray = Data[0].split('^'); const secondIndexArray = Data[1].split('^'); // 先定义变量再使用 let Name: string, Topic: string, dob: string; Name = firstIndexArray[3] || ''; Topic = secondIndexArray[0] || ''; dob = secondIndexArray[1] || ''; return { Name, Topic, dob }; // 修正原返回逻辑的笔误 } return {}; // 处理Length<=1的边界情况 };
编写测试用例覆盖空字符串分支
你需要构造**让数组对应索引不存在(或为falsy值)**的输入字符串,触发|| ''的右侧分支:
1. 覆盖Name = firstIndexArray[3] || ''分支
构造输入,使Data[0]分割后数组长度≤3(索引3为undefined):
it('should set Name to empty string when firstIndexArray has no index 3', () => { const input = 'a^b^c^^^topic^1990-01-01'; const result = service.parsedResponse(input); expect(result).toMatchObject({ Name: '', Topic: 'topic', dob: '1990-01-01' }); });
2. 覆盖Topic = secondIndexArray[0] || ''分支
构造输入,使Data[1]为空字符串(分割后数组第一个元素为"",属于falsy值):
it('should set Topic to empty string when secondIndexArray[0] is empty', () => { const input = 'a^b^c^Alice^^^'; const result = service.parsedResponse(input); expect(result).toMatchObject({ Name: 'Alice', Topic: '', dob: '' }); });
3. 覆盖dob = secondIndexArray[1] || ''分支
构造输入,使Data[1]分割后数组长度≤1(索引1为undefined):
it('should set dob to empty string when secondIndexArray has no index 1', () => { const input = 'a^b^c^Bob^^^Math'; const result = service.parsedResponse(input); expect(result).toMatchObject({ Name: 'Bob', Topic: 'Math', dob: '' }); });
4. 同时覆盖所有三个空分支
构造输入,让三个目标索引都不满足存在且为truthy的条件:
it('should set all fields to empty string when all required indices are missing', () => { const input = 'a^b^c^^^'; const result = service.parsedResponse(input); expect(result).toMatchObject({ Name: '', Topic: '', dob: '' }); });
补充说明
- 原测试用例仅覆盖了所有索引都存在的场景,新增上述用例后即可覆盖所有
|| ''的分支。 - 若你的解析函数实际返回逻辑与示例不同(比如原代码中
return { data: this.parsedResponse(...) }存在递归调用),需根据实际逻辑调整测试用例的断言部分。
内容的提问来源于stack exchange,提问作者CodeBox
相关产品推荐
相关产品推荐

