【发布时间】:2020-03-03 15:53:03
【问题描述】:
我有以下问题。我有一个单身课程。有一个调用构造函数的 getInstance 静态方法。 单例.ts:
class Singleton {
private static singletonInstance: Singleton;
private constructor(){
...doSomething;
}
public static getInstance(): Singleton {
if(!Singleton.singletonInstance){
Singleton.singletonInstance = new Singleton();
}
throw new Error('stupid error');
}
}
singleton.spec.ts:
it('getInstance should throw an error', () => {
expect(Singleton.getInstance()).toThrow(new Error('stupid error'));
})
'getInstance should throw an error' 失败,因为... getInstance() 没有抛出错误。
在控制台输出中,我注意到错误被抛出 - 它打印“愚蠢的错误”。
【问题讨论】:
-
我认为您应该验证单例创建。见这里stackoverflow.com/a/36978360/6161531
-
杰普,感谢您的评论。这只是一个例子。当然,我的单例类检查实例是否已经存在。我更新了我的示例代码,以免让其他用户感到困惑。
标签: javascript node.js typescript jestjs