单例函数的玩笑模拟

问题描述 投票:0回答:1

我在应用程序类中使用的模块中创建了一个单例类,我正在尝试更改单例包含函数的模拟实现返回值,在下面的示例中我将其命名为

isDecision

我尝试过监视单身人士

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

内联调用和嘲笑

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

我真的很难理解改变单例内部函数的实现的过程是什么。

结构示例

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

类的使用


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

export class Consumer {
  
  private _singleton: MySingleton;

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

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

Consumer

内的
测试用例
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);
    });
  });
});
unit-testing jestjs singleton
1个回答
0
投票

我找到的解决方法不仅仅是答案

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

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

如果我删除 Singleton 作为类属性并直接使用它,就像上面的笑话现在可以随意模拟

isDecision
函数。希望这种痛苦可以帮助别人

© www.soinside.com 2019 - 2024. All rights reserved.