Where is AssertionError defined in Node.js?

5.4k Views Asked by At

I'd like to have my unit tests assert that a particular function call throws an AssertionError specifically when expected, rather than that it throws an exception at all. The assertion library (expect) supports such a thing by passing an exception constructor in, but I can't seem to find where, if anywhere, the AssertionError constructor is exported. Is it intended to be an internal class only and not exposed to us? The docs contain numerous references to it, but no links.

I have a super hacky way:

let AssertionError;

try {
    const assert = require("assert");

    assert.fail();
}
catch (ex) {
    AssertionError = ex.constructor;
}

but I'm hoping there's a better way.

2

There are 2 best solutions below

3
On

After a research in the Nodejs github repo, I can tell you it is here: https://github.com/nodejs/node/blob/c75f87cc4c8d3699e081d37bb5bf47a70d830fdb/lib/internal/errors.js

AssertionError is defined like this :

class AssertionError extends Error {
  constructor(options) {
    if (typeof options !== 'object' || options === null) {
      throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
    }
    var { actual, expected, message, operator, stackStartFunction } = options;
    if (message) {
      super(message);
    } else {
      if (actual && actual.stack && actual instanceof Error)
        actual = `${actual.name}: ${actual.message}`;
      if (expected && expected.stack && expected instanceof Error)
        expected = `${expected.name}: ${expected.message}`;
      if (util === null) util = require('util');
      super(`${util.inspect(actual).slice(0, 128)} ` +
        `${operator} ${util.inspect(expected).slice(0, 128)}`);
    }

    this.generatedMessage = !message;
    this.name = 'AssertionError [ERR_ASSERTION]';
    this.code = 'ERR_ASSERTION';
    this.actual = actual;
    this.expected = expected;
    this.operator = operator;
    Error.captureStackTrace(this, stackStartFunction);
  }
}

If I were you, I would not redefined AssertionError, that is very, very hacky. I think your best bet is to extend that class to MyAssertionError or to create a twin than extends error.

Hope that helps!

0
On

Assertion error class is defined here:

assert.AssertionError

*It can be useful while testing and AsserionError is expected result:

assert.throws( FunctionThatShouldThrow_AssertionError, assert.AssertionError )