Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Docs]: toThrow fails if error object contains a cause property #15072

Open
kirkwaiblinger opened this issue May 15, 2024 · 1 comment
Open

Comments

@kirkwaiblinger
Copy link

kirkwaiblinger commented May 15, 2024

Page(s)

https://jestjs.io/docs/expect#tothrowerror

Description

When attempting to use the toThrow() method to validate an exact error message, I expected the following code to pass, according to the docs.

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

However, it fails with error

expect(received).rejects.toThrow(expected)

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

That's reasonable behavior, but it should be documented as such.

@kirkwaiblinger
Copy link
Author

This appears to occur in the synchronous case as well:

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

output:

    expect(received).toThrow(expected)

    Expected message:           "message"
    Received message and cause: "{ message: message, cause: { message: cause }}"

but doesn't occur if cause is just a string....

In summary:

  it("should pass, but doesn't, async case", async () => {
    await expect(
      (async () => {
        throw new Error('message', { cause: new Error('cause') });
      })(),
    ).rejects.toThrow(new Error('message'));
  });

  it("should pass, but doesn't, sync case", () => {
    expect(() => {
      throw new Error('message', { cause: new Error('cause') });
    }).toThrow(new Error('message'));
  });

  it('should pass, does pass', () => {
    expect(() => {
      throw new Error('message', { cause: 'cause' });
    }).toThrow(new Error('message'));
  });

TBH it seems like this may be a bug, not just undocumented behavior

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant