我正在写一个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.

当前回答

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

其他回答

为了能够创建许多测试条件,而不必每次都解析承诺,这也可以工作:

it('throws an error when it is not possible to create an user', async () => {
        const throwingFunction = () => createUser(createUserPayload)

        // This is what prevents the test to succeed when the promise is resolved and not rejected
        expect.assertions(3)

        await throwingFunction().catch(error => {
            expect(error).toBeInstanceOf(Error)
            expect(error.message).toMatch(new RegExp('Could not create user'))
            expect(error).toMatchObject({
                details: new RegExp('Invalid payload provided'),
            })
        })
    })

我一直在测试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
  });

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

你可以这样测试你的async函数:

it('should test async errors', async () =>  {        
    await expect(failingAsyncTest())
    .rejects
    .toThrow('I should fail');
});

'I should fail'字符串将匹配抛出的错误的任何部分。

如果你想在测试用例中使用try/catch方法,你可以像下面这样做。

test("some test case name with success", async () => {
 let response = null;
 let failure = null;
  // Before calling the method, make sure someAsyncFunction should be succeeded
 try {
  response = await someAsyncFunction();
 } catch(err) {
  error = err;
 }
expect(response).toEqual(SOME_MOCK_RESPONSE)
expect(error).toBeNull();
})

test("some test case name with failure", async () => {
 let response = null;
 let error = null;
 // Before calling the method, make sure someAsyncFunction should throw some error by mocking in proper way
 try {
  response = await someAsyncFunction();
 } catch(err) {
  error = err;
 }
expect(response).toBeNull();
expect(error).toEqual(YOUR_MOCK_ERROR)
})

编辑:

由于我给出的解决方案没有利用内置的笑话测试抛出功能的优势,请遵循@Lisandro https://stackoverflow.com/a/47887098/8988448建议的其他解决方案

it('should test async errors', async () =>  {        
    await expect(failingAsyncTest())
    .rejects
    .toThrow('I should fail');
});

这对我很有效

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' })
})