Jest:模拟一个特定的 ES6 class 方法

Jest: Mock a specific ES6 class method

import Store from 'electron-store';

class Test {
   private storeInstance: any;
   
   public initialise() {
     if(!Test.storeInstance) {
     Test.storeInstance = new Store({name: 'test', key:123}); // returns Default
    }
   }

   public getInstance() {
     return Test.storeInstance;
   }
}

在实现的某处,是这样使用的

   this.state = {
      view: Test.getInstance().get(
        this.props.objectName + '.' + DEFAULT_VIEW_KEY,
      )
   }

我正在尝试像下面这样模拟:

jest.spyOn(Test, 'getInstance', 'get').mockImplementation(() => 'Default')

get is a return function from electron-store which also has some arguments

expect(Test.getInstance().get({name: 'test', key: 123})).toBe('Default)

但是不工作,我做错了什么?这是使用第三方商店对象进行模拟的正确方法吗?

来自文档:

Use .toBe to compare primitive values or to check referential identity of object instances. It calls Object.is to compare values, which is even better for testing than === strict equality operator.

您应该使用 toMatchObjecttoEqualtoStrictEqual

我做错了,初始化应该被监视而不是这里的 getInstance。

这是我的最终代码版本:

jest.spyOn(DashboardStoreUtil, 'initialise');

  beforeAll(() => {
    Test.initialise();
  });