[Docs]: toThrow fails if error object contains a `cause` property
kirkwaiblinger opened this issue · 4 comments
kirkwaiblinger commented
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 commented
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