多行var声明上的Jest单元测试分支覆盖率

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多行var声明上的Jest单元测试分支覆盖率相关的知识,希望对你有一定的参考价值。

为什么在Jest覆盖率报告中将var声明(lint移动到下一行)标记为缺少分支覆盖率?

enter image description here

答案

||运算符是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', () => {
    const instance = new SomeClass();
    jest.spyOn(instance, '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, 'getFloorVar');
    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

以上是关于多行var声明上的Jest单元测试分支覆盖率的主要内容,如果未能解决你的问题,请参考以下文章

在 JEST + ENZYME 中无法达到 100% 的分支覆盖率

Jest单元测试

Jest进行前端单元测试

为啥基于 jest 的单元测试现在会导致 0% 的测试覆盖率?

web前端好帮手 - Jest单元测试工具

如何用 Jest 单元测试覆盖 TypeORM @Column 装饰器?