Skip to content

Commit

Permalink
Fix throws assertions rejecting falsy values when any: true
Browse files Browse the repository at this point in the history
Fixes #3312
  • Loading branch information
gibson042 authored Feb 28, 2024
1 parent 1d62caf commit be5000a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
4 changes: 3 additions & 1 deletion lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ export class Assertions {
}

let retval;
let threw = false;
let actual = null;
try {
retval = fn();
Expand All @@ -429,10 +430,11 @@ export class Assertions {
}));
}
} catch (error) {
threw = true;
actual = error;
}

if (!actual) {
if (!threw) {
throw fail(new AssertionError(message, {
assertion: 't.throws()',
formattedDetails: [formatWithLabel('Function returned:', retval)],
Expand Down
12 changes: 10 additions & 2 deletions test-tap/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -882,11 +882,16 @@ test('.throws()', gather(t => {
throw new Error('foo');
}), {expectBoolean: false});

// Passes when string is thrown, only when any is set to true.
// Passes when string is thrown and `expectation.any` is true.
passes(t, () => assertions.throws(() => {
throw 'foo'; // eslint-disable-line no-throw-literal
}, {any: true}), {expectBoolean: false});

// Passes when false is thrown and `expectation.any` is true.
passes(t, () => assertions.throws(() => {
throw false; // eslint-disable-line no-throw-literal
}, {any: true}), {expectBoolean: false});

// Passes because the correct error is thrown.
passes(t, () => {
const error = new Error('foo');
Expand Down Expand Up @@ -1098,9 +1103,12 @@ test('.throwsAsync()', gather(t => {
// Passes because the promise was rejected with an error.
throwsAsyncPasses(t, () => assertions.throwsAsync(Promise.reject(new Error())));

// Passes because the promise was rejected with an with an non-error exception, & set `any` to true in expectation.
// Passes because the promise was rejected with a non-error reason and `expectation.any` is true.
throwsAsyncPasses(t, () => assertions.throwsAsync(Promise.reject('foo'), {any: true})); // eslint-disable-line prefer-promise-reject-errors

// Passes because the promise was rejected with a falsy non-error reason and `expectation.any` is true.
throwsAsyncPasses(t, () => assertions.throwsAsync(Promise.reject(), {any: true}));

// Passes because the function returned a promise rejected with an error.
throwsAsyncPasses(t, () => assertions.throwsAsync(() => Promise.reject(new Error())));

Expand Down

0 comments on commit be5000a

Please sign in to comment.