无法实现 100% 的笑话覆盖率

Unable to Achieve 100% Jest line Coverage

我无法实现 100% 的 Jest Line 覆盖率。 Jest 在分支语句内有 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 语句显示为已覆盖,因为这是实际被 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);
  });

在每个测试用例中用不同的参数实例化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);
  });
});

单元测试结果:

 PASS  examples/68264949/index.test.js (10.509 s)
  68264949
    ✓ should cover if branch (2 ms)
    ✓ should cover else branch

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        12.1 s
Ran all test suites related to changed files.