jest: [Bug]: toThrow fails if error object contains a cause property

Version

29.7.0

Steps to reproduce

expect(
  (async () => {
    throw new Error("message", { cause: new Error("cause") });
  })(),
).rejects.toThrow(new Error("message"));

Expected behavior

Test should pass

Actual behavior

expect(received).rejects.toThrow(expected)

- Expected message            - 1
+ Received message and cause  + 8

Additional context

I am refiling this as a bug, because it was ignored and autoclosed as a documentation request, see https://github.com/jestjs/jest/issues/15072 🙁.

Please read through that issue first, as it also contains additional examples. IMO this may or may not be a bug, but, without documentation that speaks to this, I cannot tell, and it was unexpected to me.

Environment

macos, node 18, jest@29.7.0

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 23 (2 by maintainers)

Most upvoted comments

I am sorry for my English.

If you want to pass your test. You need compare with string or regexp or pass equal Error object

expect(
   (async () => {
       throw new Error("message", { cause: new Error("cause") });
   })(),
).rejects.toThrow("message");

or

expect(
  (async () => {
      throw new Error("message", { cause: new Error("cause") });
  })(),
).rejects.toThrow(/message/);

or

expect(
  (async () => {
      throw new Error("message", { cause: new Error("cause") });
  })(),
).rejects.toThrow(new Error("message", { cause: new Error("cause") }));

the other case

expect(
   (async () => {
       throw new Error("message");
   })(),
).rejects.toThrow(new Error("message"));