javascript - 在每个单元测试中重置打字稿单例实例
问题描述
我有一个像这样的打字稿单例类:
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;
}
}
当我想使用 jest 对其进行单元测试时,如下所示:
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');
});
});
这是失败的,因为我们在两个测试之间共享相同的实例(作为单例模式工作),因此第二个实例化是无用的。
有没有办法重置/销毁先前的实例化,以便正确检查这些默认值是否与第二个实例化一起正确设置?
解决方案
我不明白你为什么不能这样做:
MySingleton.instance = null;
const mySingleton = MySingleton.getInstance(params);
推荐阅读
- python - 如何使用 python 烧瓶应用程序将文本从输入字段发送到 MySQL 数据库
- python - 如何在字典列表中将 dict 的键值增加 1?
- jquery - 提交数据表中选定行的标题
- python - 尝试写入文件什么也没有
- greenplum - GreenPlum的Gather Motion是否存在瓶颈
- blockchain - 私有和联盟区块链中的数据输入如何受信任?
- javascript - WebPack 热重载不适用于 HTML 文件
- android - 如何在camera2api android中获取连续帧
- design-patterns - 处理数据库列的场景更改导致实体中其他地方的更改
- testing - 为什么我的空手道功能中的 Java 函数返回字符串而不是数组?