【问题标题】:How can i mock external lib who is used in Singleton's constructor ? Typescript and Jest我如何模拟在 Singleton 的构造函数中使用的外部库?打字稿和笑话
【发布时间】:2020-01-21 20:39:56
【问题描述】:

我必须测试一个单例,但在他的构造函数中我调用了一个外部方法。我该如何模拟它?

import externalLib from 'externalModule';

class MySingleton {

  public static _instance: MySingleton;

  private constructor {
    externalLib.method() // I have to mock externalLib
  }

  public static getInstance() {
    if (_instance) {
      return _instance;
    }

    return new MySingleton();
  }

}

export default MySingleton.getInstance();

谢谢。

【问题讨论】:

    标签: typescript testing mocking jestjs singleton


    【解决方案1】:

    你可以这样做(doc https://jestjs.io/docs/en/mock-functions#mocking-modules

    import extLib from 'extLib';
    
    jest.mock('extLib');
    
    test('should fetch users', () => {
      extLib.method.mockResolvedValue(MyReturnValue);
    
      // or you could use the following depending on your use case:
      // extLib.method.mockImplementation(() => Promise.resolve(MyReturnValue))
    
      // Your testing code here...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 2020-03-14
      • 2018-12-15
      • 1970-01-01
      • 2017-10-22
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多