【问题标题】:Is it possible to spyOn (jest) multiple methods in same module?是否可以在同一个模块中监视(开玩笑)多个方法?
【发布时间】:2020-08-02 13:08:12
【问题描述】:

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

// 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 多个方法吗?还有其他方法可以实现吗?

【问题讨论】:

  • 您需要在 ClassA.prototypeclassA 上模拟方法。

标签: javascript typescript unit-testing jestjs


【解决方案1】:

您需要在ClassA.prototype 上监视methodBmethodC。它们是实例方法,不是类静态方法。

例如 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

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 2019-11-24
    • 2017-07-14
    • 2018-07-06
    • 1970-01-01
    • 2021-10-31
    • 2018-03-02
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多