javascriptnode.jstypescriptjestjs

reset typescript singleton instance in each unit test


I have a typescript singleton class like so:

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

When I want to unit test it using jest, like so:

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

This is failing, because we share the same instance between the 2 tests (as the singleton pattern work), therefore the second instantiation is useless.

Is there a way to reset/destroy the previous instantiation in order to properly check if those default values are properly setted with the second intantiation?


Solution

  • I don't see why you couldn't do:

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