diff --git a/CHANGELOG.md b/CHANGELOG.md index 88e314d92508..151c2adf68a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ ### Fixes - `[babel-plugin-jest-hoist]` Use `denylist` instead of the deprecated `blacklist` for Babel 8 support ([#14109](https://github.com/jestjs/jest/pull/14109)) +- `[expect]` Check error instance type for `toThrow/toThrowError` ([#14576](https://github.com/jestjs/jest/pull/14576)) - `[jest-circus]` [**BREAKING**] Prevent false test failures caused by promise rejections handled asynchronously ([#14315](https://github.com/jestjs/jest/pull/14315)) - `[@jest/expect-utils]` Fix comparison of `DataView` ([#14408](https://github.com/jestjs/jest/pull/14408)) - `[jest-leak-detector]` Make leak-detector more aggressive when running GC ([#14526](https://github.com/jestjs/jest/pull/14526)) diff --git a/packages/expect/src/__tests__/toThrowMatchers.test.ts b/packages/expect/src/__tests__/toThrowMatchers.test.ts index 7384bf89ebac..2a1ea9a638ea 100644 --- a/packages/expect/src/__tests__/toThrowMatchers.test.ts +++ b/packages/expect/src/__tests__/toThrowMatchers.test.ts @@ -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', () => { diff --git a/packages/expect/src/toThrowMatchers.ts b/packages/expect/src/toThrowMatchers.ts index 43799cddc7de..368fa6d67a40 100644 --- a/packages/expect/src/toThrowMatchers.ts +++ b/packages/expect/src/toThrowMatchers.ts @@ -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 ? () =>