javascript - 是否可以在同一模块中监视(开 Jest )多个方法?

标签 javascript typescript unit-testing jestjs

我需要在 typescript 中监视多个方法。如何在 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 多个方法吗?还有其他方法可以实现这一目标吗?

最佳答案

你需要监视methodBmethodCClassA.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

关于javascript - 是否可以在同一模块中监视(开 Jest )多个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61315546/

相关文章:

javascript - Angularjs 智能表不适用于动态数据

node.js - NodeJS/Typescript 导出/导入的正确解释?

node.js - Jest JS 测试覆盖率数据未从 Codeship 发布到 Code Climate

angular - 类型 'Observable<Todo[]>' 缺少属性

c - 是否有用于在 Apache C 模块上运行单元测试的框架?

java - Mockito 可以捕获实现中声明的变量的参数吗?

javascript - 如何为 Splunk 日志手动设置时间戳?

JavaScript (jquery) - 单击事件中的范围问题

javascript - SVG 过渡不起作用

javascript - 带有 vue-class-component : next function does not accept callback option 的 Vue 路由器