首页 > 解决方案 > 如何测试使用 chai 或 chai-as-promised 为异步函数抛出的错误?

问题描述

我有一个功能如下:

async foo() : Promise<Object> { 
   if(...) throw new Error
}

我应该如何测试是否引发了错误?目前我正在这样做:

it("testing for error thrown", async function () {
   expect(async() => await foo()).to.throw(Error)
})

标签: javascripttypescriptunit-testingmocha.jschai

解决方案


你可以做这样的事情,如果抛出错误,测试将失败。

const foo = async (): Promise<Object> => {
  // If you want the test to fail increase x to 11
  const x = 0
  if (x > 10) {
    throw Error('Test will fail')
  }
  // Add meaningful code this is just an example
  return { some: 'object' }
}

it('testing for error thrown', async () => {
  const object = await foo()
  expect(object).toEqual({ some: 'object' })
})

推荐阅读