rejects.toThrow compares only against the message, not the error object
See original GitHub issue🐛 Bug Report or Feature Request
Unable to match on the object of the error of the rejected promise.
To Reproduce
await expect(axios(badUrl)).rejects.toThrow()
Expected behavior
Being able to access the error object and match on its objects.
await expect(axios(badUrl)).rejects.toThrow( (error) => error.reponse.status === 404)
Essentially I want to do this but without ES Lint yelling at me:
try {
await axios(url);
} catch (error) {
expect(error.response.status).toBe(404);
}
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:5 (1 by maintainers)
Top Results From Across the Web
Error is thrown but Jest's `toThrow()` does not capture the error
toThrow () expects a function fn that, when called, throws an exception. ... I added 'cause Eslint was complaining but would work without...
Read more >Node.js Error Handling Best Practices - Sematext
Promise rejections in Node.js only cause warnings. You want them to throw errors, so you can handle them properly. It's good practice to...
Read more >Promise Error Handling - JavaScript Tutorial
Promise Error Handling · function getUserById(id) { return new Promise((resolve, reject) => { resolve({ id: id, username: 'admin' }); }); } · function...
Read more >Stubs - Sinon.JS
Examples include forcing a method to throw an error in order to test error handling ... particularly on objects that you don't understand...
Read more >JavaScript Errors: Anatomy of the Error | Bugsnag Blog
Learn about the different types of JavaScript error messages, ... Not only will this code produce an error, but the console.log before the ......
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
Nice! I played around with it a bit more and it turns out you need
toMatchObject
something which is NOT an Error:I recall this being because TS compiles Errors to something odd (at least before ES2015). I remember commenting on an issue or an SO to that effect but can’t find it now. [Edit: here’s one related TS issue]
I expanded my earlier tests (and fixed some labels) using your technique:
The '!'s flag the non-intuitive lack of failure caused but TSs special treatment of Errors and its subclasses.
I agree that one can work around this but the jest expect package appears to throw away the thrown error, keeping only the message. This leads to counter-intuitive behavior like the OP’s or
.toEqual(new MyHttpException(500, "b0rked"))
acceptingnew MyHttpException(999, "b0rked")