From e4d73b99df6e5ac78ec3d147d5327bd22aa16baa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Thu, 2 Jan 2025 02:22:22 -0800 Subject: [PATCH] Improve error messages in expect().toThrow(message) Summary: Changelog: [internal] This expectation currently prints a very generic message that is hard to parse, so this change improves it a bit to account for more cases. E.g.: * Before: "Expected to throw" * After: "Expected to throw with message 'foo', but threw with message 'bar'" Differential Revision: D67738146 --- .../react-native-fantom/runtime/expect.js | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/react-native-fantom/runtime/expect.js b/packages/react-native-fantom/runtime/expect.js index 590abcd11d8c4d..7c84e8ff3c3a81 100644 --- a/packages/react-native-fantom/runtime/expect.js +++ b/packages/react-native-fantom/runtime/expect.js @@ -133,17 +133,36 @@ class Expect { ).blameToPreviousFrame(); } - let pass = false; + let thrownError; try { // $FlowExpectedError[not-a-function] this.#received(); } catch (error) { - pass = expected != null ? error.message === expected : true; + thrownError = error; } - if (!this.#isExpectedResult(pass)) { - throw new ErrorWithCustomBlame( - `Expected ${String(this.#received)}${this.#maybeNotLabel()} to throw`, - ).blameToPreviousFrame(); + + if (this.#isNot) { + if (expected != null) { + if (thrownError != null && thrownError.message === expected) { + throw new ErrorWithCustomBlame( + `Expected ${String(this.#received)} not to throw with message ${expected}"`, + ).blameToPreviousFrame(); + } + } else if (thrownError != null) { + throw new ErrorWithCustomBlame( + `Expected ${String(this.#received)} not to throw, but threw ${String(thrownError)}`, + ).blameToPreviousFrame(); + } + } else { + if (thrownError == null) { + throw new ErrorWithCustomBlame( + `Expected ${String(this.#received)} to throw`, + ).blameToPreviousFrame(); + } else if (expected != null && thrownError.message !== expected) { + throw new ErrorWithCustomBlame( + `Expected ${String(this.#received)} to throw with message "${expected}", but threw with message "${thrownError.message}"`, + ).blameToPreviousFrame(); + } } }