首页 > 解决方案 > 在每个单元测试中重置打字稿单例实例

问题描述

我有一个像这样的打字稿单例类:

export default class MySingleton {
private constructor({
    prop1,
    prop2,
    ...
  }: MySingletonConfig) {
    
    this.prop1 = prop1 ?? 'defaultProp1';
    this.prop2 = prop2;
    this.prop3 = prop3 ?? 'defaultProp3';

    /* ... some instruction ... */

    MySingleton.instance = this;
  }

  static getInstance(params?: Configuration): MySingleton {
    if (!this.instance && !params) {
      throw MySingleton.instantiationError;
    }

    if (!this.instance) {
      new MySingleton(params);

      return this.instance;
    }

    return this.instance;
  }
}

当我想使用 jest 对其进行单元测试时,如下所示:

describe('getInstance()', () => {
    test('it should return the same instance every time', () => {
      const params = {
       /* ... all the params ... */
      };

     
      const mySingleton = MySingleton.getInstance(params);

      expect(MySingleton.getInstance()).toEqual(mySingleton);
    });
    test('it should return the instance with the default value', () => {
      const params = {
       /* ... ONLY THE REQUIRED PARAMS ... */
      };
     
      const mySingleton = MySingleton.getInstance(params);

      expect(mySingleton.prop1).toEqual('defaultProp1');
      expect(mySingleton.prop3).toEqual('defaultProp3');
    });
  });

这是失败的,因为我们在两个测试之间共享相同的实例(作为单例模式工作),因此第二个实例化是无用的。

有没有办法重置/销毁先前的实例化,以便正确检查这些默认值是否与第二个实例化一起正确设置?

标签: javascriptnode.jstypescriptjestjs

解决方案


我不明白你为什么不能这样做:

MySingleton.instance = null;
const mySingleton = MySingleton.getInstance(params);

推荐阅读