Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update t.throws to accept falsy non-Error thrown values when expectation.any is true #3313

Merged
merged 1 commit into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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