assert.throws And assert.rejects Guard Errors

Assert sync throws with assert.throws and async rejections with assert.rejects, matching error classes and message patterns exactly.

JavascriptCli Tooling

Code

javascriptsnippet
28 lines
import assert from 'node:assert/strict';

function parsePercent(input) {
  const value = Number.parseFloat(input.replace(/%$/, ''));
  if (!input.includes('%')) throw new RangeError(`missing %: ${input}`);
  if (Number.isNaN(value)) throw new TypeError(`not a number: ${input}`);
  if (value < 0 || value > 100) throw new RangeError(`out of range: ${input}`);
  return value;
}

// assert.throws accepts an error class, a message regex, or both
assert.throws(() => parsePercent('42'), /missing %/);
assert.throws(() => parsePercent('abc%'), TypeError);
assert.throws(() => parsePercent('120%'), RangeError);

// When the callback does not throw, the assertion itself fails
try {
  assert.throws(() => parsePercent('50%'));
} catch (err) {
  console.log('no-throw case caught:', err.code);
}

// assert.rejects does the same job for promises that reject
async function main() {
  await assert.rejects(() => Promise.reject(new RangeError('bad input')), RangeError);
  console.log('rejection asserted');
}
main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

no-throw case caught: ERR_ASSERTION
rejection asserted

Three guard rails in parsePercent

parsePercent raises RangeError('missing %: …') when the input has no %, TypeError('not a number: …') when the stripped text parses to NaN, and RangeError('out of range: …') when value < 0 || value > 100. Each assert.throws call pins one of those paths — the regex /missing %/ for '42', the class TypeError for 'abc%', the class RangeError for '120%' — since the method accepts an error class, a message regex, or both.

What the run proves

no-throw case caught: ERR_ASSERTION
rejection asserted

parsePercent('50%') is valid, so wrapping it in assert.throws makes the assertion itself the failure: it rejects with code ERR_ASSERTION, which the surrounding try/catch reports. The async half does the same job for promises — assert.rejects(() => Promise.reject(new RangeError('bad input')), RangeError) passes because the rejection matches the class, then main() logs the confirmation line.

The line that checks async paths

await assert.rejects(() => Promise.reject(new RangeError('bad input')), RangeError);

With a matcher argument the assertion pins the rejection’s shape, not just its existence — that is what turns these calls into real tests of the three guards above.

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
It throws `RangeError` and `TypeError` before any real work runs, via the guard `value < 0 || value > 100` — handle it at the call site or let it propagate deliberately.
Is the imported module an npm package?
No — `node:assert/strict` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.