It’s a good practice to specify a number of expected assertions in async tests, so the test will fail if your assertions weren’t called at all.
test('async test', () => {
expect.assertions(3) // Exactly three assertions are called during a test
// OR
expect.hasAssertions() // At least one assertion is called during a test
// Your async tests
})
Note that you can also do this per file, outside any describe and test:
beforeEach(expect.hasAssertions)
This will verify the presense of at least one assertion per test case. It also plays nice with more specific expect.assertions(3) declarations.
async/await
test('async test', async () => {
expect.assertions(1)
const result = await runAsyncOperation()
expect(result).toBe(true)
})
Promises
Return a Promise from your test:
test('async test', () => {
expect.assertions(1)
return runAsyncOperation().then(result => {
expect(result).toBe(true)
})
})
done() callback
Wrap your assertions in try/catch block, otherwise Jest will ignore failures:
test('async test', done => {
expect.assertions(1)
runAsyncOperation()
setTimeout(() => {
try {
const result = getAsyncOperationResult()
expect(result).toBe(true)
done()
} catch (err) {
done.fail(err)
}
})
})