question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

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:open
  • Created 2 years ago
  • Reactions:2
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

6reactions
ericprudcommented, Jan 10, 2022

Nice! I played around with it a bit more and it turns out you need toMatchObject something which is NOT an Error:

const err = Promise.reject(new MyCustomError('Some Error', 'some value'))
await expect(err).rejects.toMatchObject(new MyCustomError('Some Error', 'other value')) // passes
await expect(err).rejects.toMatchObject({ message: 'Some Error', customProperty: 'other value' }) // fails

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:

// Orphans and Children from two comments back
test(" pass       Orphan==Orphan",      () => {expect(o1a1).toMatchObject(o1a2);})
test(" fail       Orphan==Orphan",      () => {expect(o1a1).toMatchObject(o2a);})
test(" pass       Child ==Child ",      () => {expect(c1a1).toMatchObject(c1a2);})
test("!fail       Child ==Child ",      () => {expect(c1a1).toMatchObject(c2a);})
test(" fail       Child ==Child'",      () => {expect(c1a1).toMatchObject(Object.assign({}, c2a));})
test(" fail str(Child)==str(Child)",    () => {expect(JSON.stringify(c1a1)).toEqual(JSON.stringify(c2a));})
test(" pass async Child==Child ", async () => {await expect(Promise.reject(c1a1)).rejects.toMatchObject(c1a2);})
test("!fail async Child==Child ", async () => {await expect(Promise.reject(c1a1)).rejects.toMatchObject(c2a);})
test(" fail async Child==Child'", async () => {await expect(Promise.reject(c1a1)).rejects.toMatchObject(Object.assign({}, c2a));})
  ✓  pass       Orphan==Orphan (3 ms)
  ✕  fail       Orphan==Orphan (5 ms)
  ✓  pass       Child ==Child 
  ✓ !fail       Child ==Child  (1 ms)
  ✕  fail       Child ==Child' (1 ms)
  ✕  fail str(Child)==str(Child) (2 ms)
  ✓  pass async Child==Child  (1 ms)
  ✓ !fail async Child==Child 
  ✕  fail async Child==Child' (1 ms)

The '!'s flag the non-intuitive lack of failure caused but TSs special treatment of Errors and its subclasses.

1reaction
ericprudcommented, Dec 25, 2021

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")) accepting new MyHttpException(999, "b0rked")

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found