【问题标题】:Jest with node and TypeScript - checking throw error from static method in Singleton用节点和 TypeScript 开玩笑 - 检查 Singleton 中静态方法的抛出错误
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢伙计!你让我今天一整天都感觉很好。我无法处理这个。
猜你喜欢
  • 2021-07-22
  • 2018-10-29
  • 2021-07-13
  • 1970-01-01
  • 2021-01-10
  • 2021-08-14
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
相关资源
最近更新 更多