函数抛出错误的 Jest 单元测试不起作用

时间:2021-03-12 14:39:26

标签: reactjs react-native unit-testing async-await jestjs

嗨,我有一个类似这样的功能:

async function getDefault(productType: ProductType = ProductType.PERSONAL_DEFAULT): Promise<OfferProduct> {
  throw new Error('getDefault products/offers api is deprecated')
}

我想测试抛出的错误字符串/值,所以我的测试看起来像这样

    it('returns expected result (deprecated)', async () => {
    const ProductsSdk = reImportSdk()
    ProductsSdk.configure(config)  
    await expect(() => ProductsSdk.getDefault()).rejects.toThrow('getDefault products/offers api is deprecated');
  })

但是,这是有效的,它在终端控制台中抱怨:

● getDefault › returns expected result (deprecated)

expect(received).rejects.toThrow()

Matcher error: received value must be a promise

Received has type:  function
Received has value: [Function anonymous]

  45 |     // const response = await ProductsSdk.getDefault()    
  46 |     // expect(() => ProductsSdk.getDefault()).toThrowError('getDefault products/offers api is deprecated')    
> 47 |     await expect(() => ProductsSdk.getDefault()).rejects.toThrow('getDefault products/offers api is deprecated');
     |                                                          ^
  48 |   })
  49 | })
  50 | 

有人知道如何修复吗?代码示例会有所帮助 谢谢

0 个答案:

没有答案