如何测试从异步函数引发的嵌套错误?

时间:2020-02-14 15:20:45

标签: javascript unit-testing async-await jestjs

考虑以下功能

const aPrivateAsyncQuery = async () => {
  try {
    return await axios.post('someURL', {query: 'someQuery'})
  } catch (error) {
    throw new Error(`A thrown error: ${error}`)
  }
}
export const aPublicAsyncFunction = async someVariable => {
  const data = await aPrivateAsyncQuery()
  if (data[someVariable]){
    return data[someVariable]
  }
  return {}
}

如何调用aPrivateAsyncQuery时测试aPublicAsyncFunction引发错误?

我目前正在进行以下测试……其中提到没有抛出任何异常。

  it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    axios.post.mockRejectedValue(new Error('bar'))

    expect(async () => { await aPublicAsyncFunction(someVariable) }).toThrow()
  })

谢谢!


编辑

以下实现效果很好:

  it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    axios.post.mockRejectedValue(new Error('bar'))

    await expect(aPublicAsyncFunction(someVariable)).rejects.toThrowError('bar')
  })

1 个答案:

答案 0 :(得分:1)

似乎期望抛出is not very well supported with async functions

根据该问题,您可以使用以下语法测试您的方法:

it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    jest.spyOn(axios, 'post')
        .mockImplementation(() => Promise.reject(new Error('bar')));

    await expect(aPublicAsyncFunction(someVariable)).rejects.toThrow(new Error('A thrown error: Error: bar'));
});