如何使用Jest模拟另一个类的实例函数

时间:2017-11-03 10:04:25

标签: node.js unit-testing typescript mocking jest

我有两个课程,例如:

//MyClass.ts
import {B} from '../MyAnotherClass'
class A {
  f1(){ }
  f2(){ 
    const instance = new B();
    instance.someBFunctionFoo(arg);
  }
}

// MyAnotherClass.ts
class B {
  someBFunctionFoo(arg){ }
  someBFunctionBar(){ }
}

我想为A类编写测试用例,但我不希望A类实际调用B类实例函数,而是调用这些函数的模拟版本。如何使用Jest实现这一目标。我正在使用typescript并针对打字稿而不是编译的js文件运行测试用例。

1 个答案:

答案 0 :(得分:1)

您可以使用jest.mock(moduleName, factory, options)模拟./MyAnotherClass模块和B类。

例如

MyClass.ts

import { B } from './MyAnotherClass';

export class A {
  f2() {
    const instance = new B();
    instance.someBFunctionFoo('arg');
  }
}

MyAnotherClass.ts

export class B {
  someBFunctionFoo(arg) {
    console.log('real someBFunctionFoo implementation');
  }
  someBFunctionBar() {
    console.log('real someBFunctionBar implementation');
  }
}

MyClass.test.ts

import { A } from './MyClass';
import { B } from './MyAnotherClass';
import { mocked } from 'ts-jest/utils';

jest.mock('./MyAnotherClass', () => {
  const mBInstance = { someBFunctionFoo: jest.fn() };
  const mB = jest.fn(() => mBInstance);
  return { B: mB };
});

describe('47093028', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', () => {
    const a = new A();
    const b = new B();
    mocked(b).someBFunctionFoo.mockImplementationOnce(() => console.log('mock someBFunctionFoo implementation'));
    a.f2();
    expect(b.someBFunctionFoo).toBeCalledWith('arg');
  });
});

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

 PASS  src/stackoverflow/47093028/MyClass.test.ts (10.577s)
  47093028
    ✓ should pass (20ms)

  console.log src/stackoverflow/47093028/MyClass.test.ts:18
    mock someBFunctionFoo implementation

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

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