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

fix: type check for error instance when used toThrowError method #14576

Merged
merged 4 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
- `[jest-leak-detector]` Make leak-detector more aggressive when running GC ([#14526](https://github.com/jestjs/jest/pull/14526))
- `[jest-util]` Make sure `isInteractive` works in a browser ([#14552](https://github.com/jestjs/jest/pull/14552))
- `[pretty-format]` [**BREAKING**] Print `ArrayBuffer` and `DataView` correctly ([#14290](https://github.com/facebook/jest/pull/14290))
- `[expect]` Check error instance type for `toThrow/toThrowError` ([#14576](https://github.com/jestjs/jest/pull/14576))

### Performance

Expand Down
6 changes: 6 additions & 0 deletions packages/expect/src/__tests__/toThrowMatchers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,16 @@ describe.each(['toThrowError', 'toThrow'] as const)('%s', toThrow => {
jestExpect(() => {
throw new Err();
})[toThrow](CustomError);
jestExpect(() => {
throw new SubErr();
})[toThrow](new SubErr());
jestExpect(() => {
throw new Err();
}).not[toThrow](Err2);
jestExpect(() => {}).not[toThrow](Err);
jestExpect(() => {
throw new SubErr();
}).not[toThrow](new SubSubErr());
});

test('did not throw at all', () => {
Expand Down
9 changes: 8 additions & 1 deletion packages/expect/src/toThrowMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,17 @@ const toThrowExpectedObject = (
const expectedMessageAndCause = createMessageAndCause(expected);
const thrownMessageAndCause =
thrown === null ? null : createMessageAndCause(thrown.value);
const isCompareErrorInstance = thrown?.isError && expected instanceof Error;
const isExpectedCustomErrorInstance =
expected.constructor.name !== Error.name;

const pass =
thrown !== null &&
thrown.message === expected.message &&
thrownMessageAndCause === expectedMessageAndCause;
thrownMessageAndCause === expectedMessageAndCause &&
(!isCompareErrorInstance ||
!isExpectedCustomErrorInstance ||
thrown.value instanceof expected.constructor);

const message = pass
? () =>
Expand Down