我有以下问题。我有单身人士班。有一个getInstance静态方法可以调用构造函数。singleton.ts:
class Singleton {
private constructor(){
...doSomething;
}
public static getInstance(): Singleton {
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()没有引发错误。
在控制台输出上,我可以注意到该错误被抛出-它显示'愚蠢的错误'。
根据文档here中提到的示例,您需要提供一个匿名函数来对此进行测试:
it('getInstance should throw an error', () => {
expect(() => Singleton.getInstance()).toThrow(new Error('stupid error'));
})
基本上,玩笑会调用给定的函数,然后确定它是否引发错误。在您的情况下,由于Singleton.getInstance()
已引发错误,因此该结果不可调用。