From d938ca053a960ba869c5df12c976aa31a118e88b Mon Sep 17 00:00:00 2001 From: Luca Pizzini Date: Mon, 26 Sep 2022 15:57:42 +0200 Subject: [PATCH] fix: adjusted assert.throws error format fixes #13264 --- e2e/failures/__tests__/assertionError.test.js | 17 +++++++++++++++++ .../jest-circus/src/formatNodeAssertErrors.ts | 9 +++++++++ .../jest-jasmine2/src/assertionErrorMessage.ts | 8 ++++++++ 3 files changed, 34 insertions(+) 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') +