diff --git a/e2e/failures/__tests__/assertionError.test.js b/e2e/failures/__tests__/assertionError.test.js index cc5909918e5b..ee9e62c1ed05 100644 --- a/e2e/failures/__tests__/assertionError.test.js +++ b/e2e/failures/__tests__/assertionError.test.js @@ -76,6 +76,23 @@ test('assert.throws', () => { assert.throws(() => {}); }); +test('assert.throws with different error messages', () => { + assert.throws( + () => { + throw new Error('message 1'); + }, + { + message: 'message 2', + }, + ); +}); + +test('assert.throws with different error types', () => { + assert.throws(() => { + throw new SyntaxError('message 1'); + }, TypeError); +}); + test('async', async () => { assert.equal('hello\ngoodbye', 'hello', 'hmmm'); }); diff --git a/packages/jest-circus/src/formatNodeAssertErrors.ts b/packages/jest-circus/src/formatNodeAssertErrors.ts index 4ea53b16c660..23cfa07e0b51 100644 --- a/packages/jest-circus/src/formatNodeAssertErrors.ts +++ b/packages/jest-circus/src/formatNodeAssertErrors.ts @@ -150,6 +150,15 @@ function assertionErrorMessage( } if (operatorName === 'throws') { + if (error.generatedMessage) { + // Thrown error do not match expected one + return ( + buildHintString(assertThrowingMatcherHint(operatorName)) + + chalk.reset(error.message) + + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + + trimmedStack + ); + } return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function to throw an error.\n') + diff --git a/packages/jest-jasmine2/src/assertionErrorMessage.ts b/packages/jest-jasmine2/src/assertionErrorMessage.ts index 7c149088f43f..3408af159c92 100644 --- a/packages/jest-jasmine2/src/assertionErrorMessage.ts +++ b/packages/jest-jasmine2/src/assertionErrorMessage.ts @@ -111,6 +111,14 @@ function assertionErrorMessage( } if (operatorName === 'throws') { + if (error.generatedMessage) { + return ( + buildHintString(assertThrowingMatcherHint(operatorName)) + + chalk.reset(error.message) + + chalk.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + + trimmedStack + ); + } return ( buildHintString(assertThrowingMatcherHint(operatorName)) + chalk.reset('Expected the function to throw an error.\n') +