我正在写一个async测试,期望async函数抛出像这样:

it("expects to have failed", async () => {
  let getBadResults = async () => {
    await failingAsyncTest()
  }
  expect(await getBadResults()).toThrow()
})

但玩笑只是失败而不是通过测试:

 FAIL  src/failing-test.spec.js
  ● expects to have failed

    Failed: I should fail!

如果我重写这个测试,看起来像这样:

expect(async () => {
  await failingAsyncTest()
}).toThrow()

我得到这个错误,而不是通过测试:

expect(function).toThrow(undefined)

Expected the function to throw an error.
But it didn't throw anything.

当前回答

我一直在测试Firebase的云功能,这是我得出的结论:

test("It should test async on failing cloud functions calls", async () => {
    await expect(async ()=> {
        await failingCloudFunction(params)
    })
    .rejects
    .toThrow("Invalid type"); // This is the value for my specific error
  });

这是建立在丽桑德罗的答案之上的。

其他回答

我一直在测试Firebase的云功能,这是我得出的结论:

test("It should test async on failing cloud functions calls", async () => {
    await expect(async ()=> {
        await failingCloudFunction(params)
    })
    .rejects
    .toThrow("Invalid type"); // This is the value for my specific error
  });

这是建立在丽桑德罗的答案之上的。

我想在此基础上补充一点,说明您正在测试的函数必须抛出一个实际的Error对象抛出新的Error(…)。Jest似乎不能识别你是否抛出了一个像throw ' an error occurred!'这样的表达式。

这对我很有效

it("expects to have failed", async () => {
  let getBadResults = async () => {
    await failingAsyncTest()
  }
  expect(getBadResults()).reject.toMatch('foo')
  // or in my case
  expect(getBadResults()).reject.toMatchObject({ message: 'foo' })
})
await expect(async () => { 
    await someAsyncFunction(someParams); 
}).rejects.toThrowError("Some error message");

我们必须将代码包装在函数中以捕获错误。在这里,我们期望someAsyncFunction抛出的错误消息应该等于“一些错误消息”。我们也可以调用异常处理程序

await expect(async () => { 
    await someAsyncFunction(someParams); 
}).rejects.toThrowError(new InvalidArgumentError("Some error message"));

阅读更多信息https://jestjs.io/docs/expect#tothrowerror

test("它应该在云函数调用失败时测试async ", async () => { failingCloudFunction (params)。Catch (e => { 期望(e.message)。托比(无效的类型) }) });