使用节点和TypeScript进行Jest-检查Singleton中静态方法的抛出错误



我有以下问题。我有一个单例类。有一个getInstance静态方法调用构造函数。singleton.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应该抛出错误"失败,因为。。。getInstance((未引发错误。

在控制台输出上,我可以注意到错误是抛出的——它打印出"愚蠢的错误"。

根据这里文档中提到的示例,您需要提供一个匿名函数来测试这一点:

it('getInstance should throw an error', () => {
expect(() => Singleton.getInstance()).toThrow(new Error('stupid error'));
})

基本上,jest调用给定的函数,然后确定它是否抛出错误。在您的情况下,由于Singleton.getInstance()已经抛出错误,因此结果是不可调用的。

最新更新