0

I have a singleton class created in a module consumed within a class of an app, I am attempting to change the mock implementations return value of the singletons contained function, in the example below I've named it isDecision.

I have tried spying on the singleton

jest.spyOn(MySingleton, "getInstance").mockImplementation({
  isDecision: jest.fn(() => false),
});

calling and mocking inline

MySingleton.getInstance().isDecision.mockReturnValue(false);

I am really struggling to understand what the process is for changing the implementation of a singleton inner functions is.

EXAMPLE STRUCTURE

export default class MySingleton {
    
  private static _instance: MySingleton;

  static getInstance(): MySingleton {
    if (!MySingleton._instance) {
      MySingleton._instance = new MySingleton();
    }

    return MySingleton._instance;
  }

  isDecision(): boolean {
    return true;
  }
}

class usage


import { MySingleton } from "@my-singleton";

export class Consumer {
  
  private _singleton: MySingleton;

  constructor() {
   this._singleton = MySingleton.getInstance();
  }

  utilityFunction(): boolean {
    return this._singleton.isDecision();
  }
}

test cases within Consumer for isDecision

jest.mock("@my-singleton", () => ({
  __esModule: true,
  MySingleton: {
    getInstance: jest.fn().mockImplementation(() => ({
      isDecision: jest.fn(() => true),
    })),
  },
}));

describe("Consumer", () => {
  let consumer;

  beforeEach(() => {
    consumer = new Consumer();
  });
  
  describe("test decision is true case", () => {
    
    test("should return true", () => {
      const decision = consumer.utilityFunction(); 
      expect(decision).toBe(true);
    });
  });

  describe("test decision is false case", () => {
    
    beforeEach(() => {
      // how to change IsDecsion of singleton to return false?
    });

    test("should return true", () => {
      const decision = consumer.utilityFunction(); 
      expect(decision).toBe(false);
    });
  });
});

1 Answer 1

0

I found a workaround more than an answer

import { MySingleton } from "@my-singleton";

export class Consumer {
  utilityFunction(): boolean {
    return MySingleton.getInstance().isDecision();
  }
}

If I remove the Singleton as a class property and use it directly as above jest can now mock the isDecision function at will. Hope this pain helps someone else

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.