From 7e2b1a947436f94c036a51d88686605846f8a136 Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Mon, 13 May 2024 22:18:38 +0100 Subject: [PATCH] fix: raise a nicer error when non-object errors are matched (#294) When a promise is rejected, we currently incorrectly assume the rejection reason is an object consumable by check-error (i.e. an `Error` or similar). This change basically checks strict equality on the matcher and the thrown error first (such that `rejectedWith(undefined)` would work). It then falls back to the original logic only if both the matcher and the reason are truthy. Fixes #263 --- lib/chai-as-promised.js | 5 ++++- test/assert-promise-specific.js | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/chai-as-promised.js b/lib/chai-as-promised.js index 0d0cb54..4ffdb2e 100644 --- a/lib/chai-as-promised.js +++ b/lib/chai-as-promised.js @@ -215,7 +215,10 @@ export default function (chai, utils) { : checkError.compatibleConstructor(reason, errorLike)); const errMsgMatcherCompatible = - errMsgMatcher && checkError.compatibleMessage(reason, errMsgMatcher); + errMsgMatcher === reason || + (errMsgMatcher && + reason && + checkError.compatibleMessage(reason, errMsgMatcher)); const reasonName = getReasonName(reason); diff --git a/test/assert-promise-specific.js b/test/assert-promise-specific.js index fc03fc1..7c2f23a 100644 --- a/test/assert-promise-specific.js +++ b/test/assert-promise-specific.js @@ -289,5 +289,20 @@ describe('Assert interface:', () => { }); }); }); + + describe('with undefined error', () => { + beforeEach(() => { + promise = Promise.reject(); + }); + + describe('.isRejected(promise)', () => { + shouldPass(() => assert.isRejected(promise)); + shouldPass(() => assert.isRejected(promise, undefined)); + shouldFail({ + op: () => assert.isRejected(promise, 'Error'), + message: "to be rejected with an error including 'Error' but got ''" + }); + }); + }); }); });