Javascript 使用Jest.js模拟复杂模块

Javascript 使用Jest.js模拟复杂模块,javascript,jestjs,web3,Javascript,Jestjs,Web3,这就是我想要模拟的模块的样子: class TheModule { constructor() { this.subClass = new SubClass(); } } class SubClass { constructor() { this.someMethod = () => 'Did Something great'; } } module.exports = TheModule; 这是我要测试的模块用法: const TheModule

这就是我想要模拟的模块的样子:

class TheModule {
  constructor() {
    this.subClass = new SubClass();
  }
}

class SubClass {
  constructor() {
    this.someMethod = () => 'Did Something great'; 
  }
}

module.exports = TheModule;
这是我要测试的模块用法:

const TheModule = require('./TheModule');

const method = () => {
  const theModule = new TheModule();
  return theModule.subClass.someMethod();
}

module.exports = method;
这是我的测试:

describe('method test', () => {
  
  it('should return "Test pass"', () => {
    jest.doMock('./TheModule');
    const theModuleMock = require('./TheModule');
    const method = require('./TheModuleUsage');
    const mock = () => 'Test pass';
    theModuleMock.subClass.someMethod.mockImplementation(() => mock);
    expect(method()).toEqual('Test pass');
  });
  
});
当我运行此测试时,我得到
TypeError:无法读取未定义的属性“someMethod”


是否可以在不更改
模块
实现的情况下模拟此模块?

如果要导出
子类
,则可以在不更改
模块
的情况下模拟此模块,但在您的情况下,应使用factory显式模拟
模块
中的
子类
属性,例如:

describe('method test', () => {

  it('should return "Test pass"', () => {
    let mockedSomeMethod = jest.fn().mockImplementation(() => 'Test pass');
    jest.doMock('./TheModule', () => {
      // mock constructor
      return jest.fn().mockImplementation(() => {
        return { subClass: { someMethod: mockedSomeMethod  } }
      });
    });
    const method = require('./TheModuleUsage');
    expect(method()).toEqual('Test pass');
  });
});