这是一个非常奇怪的问题(哎呀)。
我正在使用一个库,该库根据其过去的预期用例使用单例。但是,由于一个新的用例,我想知道是否有办法作弊。我不想修改库,因为它可能会影响其他消费者。
import SingletonLibraryStuff from 'library'; // has a bunch of singletons in it
// first instance
import SingletonLibraryStuff from 'library'; // has a bunch of singletons in it
// second instance
问题:
旧用
import { LibraryInit, LibraryAction } from 'singleton-library';
const things = [thing1, thing2, thing3];
LibraryInit(things);
LibraryAction.doSomething(); // action on thing1, thing2, thing3
新用途
import { LibraryInit, LibraryAction } from 'singleton-library';
LibraryInit([thing1]);
LibraryInit([thing2]);
[thing1, thing2].forEach(_ => LibraryAction.doSomething()) // breaks due to singletons in 'singleton-library'
您可以使用一种称为模块模拟的技术来创建单例类的多个实例,而无需修改库代码。模块模拟是 Jest 的一个特性,Jest 是一个流行的 JavaScript 测试框架,但它也可以在 Jest 之外用于其他目的。
要使用模块模拟,您必须为库创建一个模拟模块,并将单例实例替换为模拟实例。这是一个例子:
// Create a mock instance of the singleton class
const mockSingleton = {
// Define the methods and properties of the mock instance
// ...
};
// Create a mock module for the library and replace the singleton instance
jest.mock('library', () => {
return {
getInstance: jest.fn(() => {
return mockSingleton;
}),
};
});
// Use the library in your code
import SingletonLibraryStuff from 'library'; // First instance
import SingletonLibraryStuff from 'library'; // Second instance
// The calls to getInstance() will return the same mock instance
在此示例中,库的模拟模块将 getInstance() 方法替换为始终返回相同模拟实例的模拟实现。当您在代码中导入库时,对 getInstance() 的调用将返回模拟实例而不是原始单例实例,从而有效地允许您创建单例的多个实例。