关于var声明的Jest /伊斯坦布尔单元测试分支覆盖范围

为什么在伊斯坦布尔覆盖率报告中将var声明标记为缺少分支覆盖范围?

关于var声明的Jest /伊斯坦布尔单元测试分支覆盖范围

xiejian444 回答:关于var声明的Jest /伊斯坦布尔单元测试分支覆盖范围

||运算符是if...else..条件语句。您需要测试每个分支。

例如

index.ts

export class SomeClass {
  INCREMENT = 1;
  MIN_SCALE = 2;
  public zoomOut(this: any): void {
    const scaleVal = this.getFloorVar() || this.INCREMENT || this.MIN_SCALE;
    this.updateZoom(scaleVal);
  }

  public getFloorVar() {
    return 0;
  }

  public updateZoom(scaleVal) {
    console.log(scaleVal);
  }
}

index.spec.ts

import { SomeClass } from './';

describe('SomeClass',() => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should pass - 1',() => {
    const instance = new SomeClass();
    jest.spyOn(instance,'getFloorVar');
    jest.spyOn(instance,'updateZoom');
    instance.zoomOut();
    expect(instance.getFloorVar).toBeCalledTimes(1);
    expect(instance.updateZoom).toBeCalledWith(1);
  });

  it('should pass - 2','getFloorVar').mockReturnValueOnce(22);
    jest.spyOn(instance,'updateZoom');
    instance.zoomOut();
    expect(instance.getFloorVar).toBeCalledTimes(1);
    expect(instance.updateZoom).toBeCalledWith(22);
  });

  it('should pass - 3',() => {
    const instance = new SomeClass();
    instance.INCREMENT = 0;
    jest.spyOn(instance,'updateZoom');
    instance.zoomOut();
    expect(instance.getFloorVar).toBeCalledTimes(1);
    expect(instance.updateZoom).toBeCalledWith(2);
  });
});

具有100个覆盖率报告的单元测试结果:

PASS  src/stackoverflow/59330476/index.spec.ts (11.68s)
  SomeClass
    ✓ should pass - 1 (30ms)
    ✓ should pass - 2 (3ms)
    ✓ should pass - 3 (2ms)

  console.log src/stackoverflow/59330476/index.ts:407
    1

  console.log src/stackoverflow/59330476/index.ts:407
    22

  console.log src/stackoverflow/59330476/index.ts:407
    2

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed,1 total
Tests:       3 passed,3 total
Snapshots:   0 total
Time:        12.984s

enter image description here

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59330476

本文链接:https://www.f2er.com/2924058.html

大家都在问