【发布时间】:2020-12-31 02:47:26
【问题描述】:
我有一个像这样的打字稿单例类:
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。 @Taplar 他正在尝试测试 getInstance 函数。但是,如果有实例,则行为会发生变化,因此他无法正确验证这一点。
-
@chingucoding 我明白这一点。我的意思是,如果值没有改变,它们将是默认值。因此,如果
getInstance方法的描述有一个beforeAll调用 getInstance 以创建默认实例,那么“相同实例”测试和“默认值”测试都可以使用相同的东西并且工作。唯一的复杂情况是,如果 jest/jasmine 设置为以随机顺序运行规范。 -
我对打字稿不是很熟悉。有没有办法使实例“受保护”?这样,您可以编写一个扩展
MySingleton类的TestMySingleton类,它有一个销毁实例的方法? -
如果哪些值没有改变?当其中一个测试成功时,设置了 MySingleton 的实例属性,下一次测试不会更改实例,因为您没有清除实例。问题是关于如何重置该实例,那么如何实现 beforeAll
标签: javascript node.js typescript jestjs