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