我无法实现 100% 的 Jest Line 覆盖率。 Jest 在行中显示未覆盖的行 a 在分支语句内有一个 return 语句。
export class Galactic {
constructor(earthAge) {
this.earthAge = earthAge;
this.mercuryAge = 0; //.24 earth years
this.venusAge = 0; //.62
this.marsAge = 0; //1.88
this.jupiterAge = 0; //11.86
this.averageLife = 65;
}
lifeExpOnMars() {
if (this.earthAge > this.averageLife) {
let surpassedYears = (this.earthAge - this.averageLife) * 1.88;
return Math.floor(surpassedYears);
} else {
let remainingYears = this.averageLife - this.earthAge;
return Math.floor(remainingYears * 1.88);
}
}
}
我在函数中的第一个 return 语句没有显示 Jest 覆盖率,因为该代码没有运行,因为我的输入通过第一个 if 语句不为真。第二个 return 语句显示为已覆盖,因为这是实际返回的代码,因为第一个 if 语句根据我输入的 earthAge 小于 averageLife 为假。
我需要帮助弄清楚我可以编写一个测试来覆盖第一个 return 语句,因为它不需要执行,因为不满足条件。
参考测试:
describe('Galactic', function(){
let galacticAge;
beforeEach(function(){
galacticAge = new Galactic(25)
test('return life expectancy on Mars', function(){
expect(galacticAge.lifeExpOnMars()).toEqual(75);
});
答案 0 :(得分:1)
在每个测试用例中使用不同的参数实例化 public async Task<IActionResult> AddRequest([FromForm]Request model)
{
//...
。让 Galactic
条件语句变为真。
if
:
index.js
export class Galactic {
constructor(earthAge) {
this.earthAge = earthAge;
this.mercuryAge = 0; //.24 earth years
this.venusAge = 0; //.62
this.marsAge = 0; //1.88
this.jupiterAge = 0; //11.86
this.averageLife = 65;
}
lifeExpOnMars() {
if (this.earthAge > this.averageLife) {
let surpassedYears = (this.earthAge - this.averageLife) * 1.88;
return Math.floor(surpassedYears);
} else {
let remainingYears = this.averageLife - this.earthAge;
return Math.floor(remainingYears * 1.88);
}
}
}
:
index.test.js
单元测试结果:
import { Galactic } from './';
describe('68264949', () => {
it('should cover if branch', () => {
const galactic = new Galactic(100);
const actual = galactic.lifeExpOnMars();
expect(actual).toEqual(65);
});
it('should cover else branch', () => {
const galactic = new Galactic(25);
const actual = galactic.lifeExpOnMars();
expect(actual).toEqual(75);
});
});