开玩笑地将模拟类传递给构造函数

时间:2020-05-04 16:12:52

标签: javascript unit-testing mocking jestjs

假设我有

class A {
  constructor(classB) {

  }
}

class B {

}

如何在测试中实例化class A并将模拟的class B传递给它?基本上我想做

a = new A(mockedClassB);

具体来说,我的问题是关于如何创建mockedClassB的,因此我可以将其传递给A构造函数。

1 个答案:

答案 0 :(得分:2)

这是一个解决方案:

a.js

export default class A {
  classB;
  constructor(classB) {
    this.classB = classB;
  }

  getName() {
    return this.classB.getName();
  }
}

b.js

export default class B {
  getName() {
    return 'real name from b';
  }

  // add a new method later
  getAge() {
    return 23;
  }
}

a.test.js

import A from './a';
import B from './b';
jest.mock('./b');

describe('61596704', () => {
  it('should pass', () => {
    const mockedClassBInstance = new B();
    mockedClassBInstance.getName.mockReturnValueOnce('mocked name from b');
    const a = new A(mockedClassBInstance);
    const actual = a.getName();
    expect(actual).toEqual('mocked name from b');
  });

  it('getAge method of B should be mocked as well', () => {
    const mockedClassBInstance = new B();
    jest.isMockFunction(mockedClassBInstance.getAge);
  });
});

单元测试结果:

 PASS  stackoverflow/61596704/a.test.js (8.913s)
  61596704
    ✓ should pass (3ms)
    ✓ getAge method of B should be mocked as well (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.486s