jest: async/ await toThrow is not working
next test
async function check() {
throw new Error('Test');
}
expect(async () =>
await check()
).toThrow();
will fail and don’t catch error properly (I am using latest version of jest)
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 108
- Comments: 22 (5 by maintainers)
Commits related to this issue
- Fix a jest error Every time I did `await expect(...).rejects.toThrow(...)` jest would throw. Error here: https://travis-ci.org/artf/grapesjs/jobs/600715489#L1147 Many comments in the jest github is... — committed to tom-sherman/grapesjs by tom-sherman 5 years ago
- Fix tests https://github.com/facebook/jest/issues/1700#issuecomment-477393675 — committed to zkopru-network/blind-find by mhchia 3 years ago
Instead of
this works:
Yeah the syntax is awkward…
Should work as well
You can also write:
Yes, this isn’t supported currently. See https://github.com/facebook/jest/issues/1377
Should work as well
can work
version
23.4.2
23.1.2
is what I do.
The following worked for me as well:
See: https://facebook.github.io/jest/docs/en/tutorial-async.html#rejects
In case someone throw anything different from instance Error class and struggle to use advise from that thread (as I did).
toThrow()
will check what value thrown is the instance of Error class, and if it is not - throw will not be detected. This wasn’t obvious from the docs and common sense. This will fail, even though it clearly throws:but this will work (not sure if there is a better way):
Adding to the list of workarounds. If you like me want to catch a specific error type, and don’t care about the message:
A slightly better way is to use
toBeDefined()
instead oftoBeTruthy()
:Here’s an explicit test that assures it will definitely break if it does NOT throw and matches specific error.
@Marchelune When you write
class CustomErrorType extends Error {}
you haven’t actually defined a new class. If you give CustomErrorType a body, even just a constructor that does nothing but call super(), it will work.Hi ! I might be doing something wrong, but I still have an issue with custom errors in async calls. Consider the following:
then the test fails with the following output:
So the test fails - whilst it works perfectly when the thrown class is
Error
. When I try to extendError
withthen the error is
Any clue on something what is wrong in that sample ? I’m using jest 23.4.2.
Problem about this is that your test will pass if the code never has errors.
So this test would not really offer much value as it’s expected results are varied based on whether the code it’s testing has an error or not.
Tests should have a negative flow or a positive flow and we should only test what is needed to test. This sort of randomness isn’t the greatest.
@Karabur typo
toBeThruthy
should betoBeTruthy
You need to invoke it to give it the actual promise