简体   繁体   English

使用 Jest.js 模拟复杂模块

[英]Mocking complex module using Jest.js

This is what the module I want to mock looks like:这是我想要模拟的模块的样子:

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

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

module.exports = TheModule;

This is TheModule usage I want to test:这是我要测试的TheModule用法:

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

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

module.exports = method;

This is my test:这是我的测试:

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');
  });
  
});

When I run this test I get TypeError: Cannot read property 'someMethod' of undefined当我运行这个测试时,我得到TypeError: Cannot read property 'someMethod' of undefined

Is it possible to mock this module without changing TheModule implementation?是否可以在不更改TheModule实现的情况下模拟此模块?

If you will export SubClass you can mock it without changing TheModule but in your case you should mock SubClass property in TheModule explicitly with factory for example:如果您将导出SubClass您可以在不更改TheModule的情况下模拟它,但在您的情况下,您应该使用 factory 显式模拟TheModule SubClass属性,例如:

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');
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM