Async / Await expect().toThrow() does not work as expected
See original GitHub issueI’m trying to assert that a promise throws an error with Async / Await.
async function throws () {
throw new Error('hello world')
}
test('promise throws', async () => {
expect(async () => {
await throws()
}).toThrow()
})
This is what I’m getting:
● promise throws
expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.
Any thoughts? Does Jest not support this? Or am I using it incorrectly?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:14
- Comments:6
Top Results From Across the Web
Can you write async tests that expect toThrow? - Stack Overflow
You can test your async function like this: it('should test async errors', async () => { await expect(failingAsyncTest()) .rejects .
Read more >Testing Asynchronous Code - Jest
If the expect statement fails, it throws an error and done() is not called. If we want to see in the test log...
Read more >API Reference | Vitest
When a test function returns a promise, the runner will wait until it is ... test('should work as expected', () => { expect(Math.sqrt(4))....
Read more >How to Throw Errors From Async Functions in JavaScript?
js Person methods › it throws when url is not a string assert.throws(function) Expected the function to throw an error. But it didn...
Read more >expect(await fn()) vs await expect(fn()) for error tests with chai ...
Pulling the await someFn() result out into a variable helps make this clearer as to what's going on. As we are not catching...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
What?
This is solved, please read the docs before commenting on old issues. https://jestjs.io/docs/en/asynchronous#resolves-rejects
The important thing in the solution is to
await
theexpect
. Otherwise your checks will always pass. Alternatively you could also return the expect like they do it in the docs.