是否可以在同一模块中间谍(开玩笑)多个方法?

时间:2020-04-20 05:16:17

标签: javascript typescript unit-testing jestjs

我需要监视打字稿中的多个方法。如何在打字稿中实现?

// classA.ts
export class ClassA {
  public methodA() {
    this.methodB();
    this.methodC();
    return "ClassA";
  }
  public methodB() {}
  public methodC() {}
}

// classATest.ts
import {ClassA} from './classA';

it('Sample Test', async () => {
  const spyOn1 = jest.spyOn(ClassA, 'methodB');
    spyOn1.mockImplementation(() => {return () => {}});
    const spyOn2 = jest.spyOn(ClassA, 'methodC');
    spyOn2.mockImplementation(() => {return () => {}});

    const classA = new ClassA();
    expect(classA.methodA()).toEqual('ClassA');
});

我收到错误提示-Argument of type '"methodC"' is not assignable to parameter of type '"methodB" | "prototype"'.

我们不能在一个类上使用spyOn多个方法吗?还有其他方法可以实现吗?

1 个答案:

答案 0 :(得分:2)

您需要监视methodB上的methodCClassA.prototype。它们是实例方法,类静态方法。

例如 ClassA.ts

export class ClassA {
  public methodA() {
    this.methodB();
    this.methodC();
    return 'ClassA';
  }
  public methodB() {}
  public methodC() {}
}

ClassA.test.ts

import { ClassA } from './classA';

describe('61315546', () => {
  it('Sample Test', async () => {
    const spyOn1 = jest.spyOn(ClassA.prototype, 'methodB');
    spyOn1.mockImplementation(() => {
      return () => {};
    });
    const spyOn2 = jest.spyOn(ClassA.prototype, 'methodC');
    spyOn2.mockImplementation(() => {
      return () => {};
    });

    const classA = new ClassA();
    expect(classA.methodA()).toEqual('ClassA');
  });
});

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

 PASS  stackoverflow/61315546/ClassA.test.ts (12.1s)
  61315546
    ✓ Sample Test (3ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |      50 |     100 |                   
 ClassA.ts |     100 |      100 |      50 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.974s
相关问题