首页 > 解决方案 > 无法实现 100% 的 Jest 线路覆盖率

问题描述

我无法实现 100% 的 Jest 线路覆盖率。Jest 在分支语句中有返回语句的行上显示未覆盖的行。

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 语句传递的输入不正确。第二个返回语句显示为已覆盖,因为这是实际返回的代码,因为第一个 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);
  });

标签: javascripttestingjestjstdd

解决方案


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.

推荐阅读