我如何模拟在 Singleton 的构造函数中使用的外部库?打字稿和笑话

How can i mock external lib who is used in Singleton's constructor ? Typescript and Jest

我必须测试一个单例,但在他的构造函数中我调用了一个外部方法。我怎样才能嘲笑它?

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();

谢谢。

你可以这样做(文档 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...
});