Search code examples
node.jsnode-assert

Unexpected result from assert.fail


I'm using the assert module for throwing pre-condition errors. It seems to me based on the documentation that assert.fail(message) should throw an exception for which the message property is just the message passed in. However, it's being set to whatever messaged is wrapped in single quotes and followed by undefined undefined.

Is this a bug in the version of assert I'm using (1.4.1), is this a bug in the documentation, or is my understanding wrong?

My code:

$ cat assert-test.js
assert = require ("assert")

try {
    assert.fail("boom")
}
catch (ex) {
    console.log(ex)
}

$ node assert-test.js 
{ [AssertionError: 'boom' undefined undefined]
  name: 'AssertionError',
  actual: 'boom',
  expected: undefined,
  operator: undefined,
  message: '\'boom\' undefined undefined',
  generatedMessage: true }

This is the part of the documentation that seems relevant to me.

If message is provided only it will be used as the error message, the other arguments will be stored as properties on the thrown object

This also seems relevant.

Note: Is the last two cases actual, expected, and operator have no influence on the error message.

assert.fail(); // AssertionError [ERR_ASSERTION]: Failed

assert.fail('boom'); // AssertionError [ERR_ASSERTION]: boom

assert.fail('a', 'b'); // AssertionError [ERR_ASSERTION]: 'a' != 'b'

Solution

  • I was a little curious because I didn't know what you meant by assert v. 1.4.1 since assert is part of the standard Node library.

    It looks like you are using this: https://www.npmjs.com/package/assert instead of the actual Node version — I assume you doing that because you want to use it in a browser or something.

    Looking over their source code, it's clear they don't try to mimic the current Node behavior, but instead just print a concatenation of the actual, expected when message isn't provided as a third parameter to assert.fail(). I don't know if this is a bug, intentional, or they are just behind the current version of Node (although the fact that they are failing their test makes me suspicious). But you are correct, the behavior of this module is not in sync with current Node docs, which (at least in v.8.6.0) works as documented for me.