如何检查是否使用笑话已被调用的方法?

时间:2019-12-24 09:09:00

标签: typescript jestjs

我在函数内部有一个函数。我试图检查调用或不使用笑话的内部功能。但所有测试用例均失败。

Sample.ts

export class Sample
{
    update():void
     {
      this.update1()
      this.update2()
     }

     protected update1():void
     {
       console.log('hai');
     }

      protected update2():void
     {
       console.log('hello');
     }
}

如何检查update()内部函数是否被使用instp

1 个答案:

答案 0 :(得分:1)

您可以使用jest.spyOn来完成此操作。

例如

sample.ts

export class Sample {
  update(): void {
    this.update1();
    this.update2();
  }

  protected update1(): void {
    console.log('hai');
  }

  protected update2(): void {
    console.log('hello');
  }
}

sample.test.ts

import { Sample } from './sample';

describe('59466379', () => {
  it('should pass', () => {
    // @ts-ignore
    const update1 = jest.spyOn(Sample.prototype, 'update1');
    // @ts-ignore
    const update2 = jest.spyOn(Sample.prototype, 'update2');
    const instance = new Sample();
    instance.update();
    expect(update1).toBeCalledTimes(1);
    expect(update2).toBeCalledTimes(1);
    update1.mockRestore();
    update2.mockRestore();
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/59466379/sample.test.ts (10.71s)
  59466379
    ✓ should pass (16ms)

  console.log src/stackoverflow/59466379/sample.ts:317
    hai

  console.log src/stackoverflow/59466379/sample.ts:327
    hello

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

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