assert: put info in err.message, not err.name
authorRyan Doenges <rhdoenges@gmail.com>
Sun, 14 Apr 2013 01:48:00 +0000 (18:48 -0700)
committerisaacs <i@izs.me>
Thu, 18 Apr 2013 22:08:35 +0000 (15:08 -0700)
4716dc6 made assert.equal() and related functions work better by
generating a better toString() from the expected, actual, and operator
values passed to fail(). Unfortunately, this was accomplished by putting
the generated message into the error's `name` property. When you passed
in a custom error message, the error would put the custom error into
`name` *and* `message`, resulting in helpful string representations like
"AssertionError: Oh no: Oh no".

This commit resolves that issue by storing the generated message in the
`message` property while leaving the error's name alone and adding
a regression test so that this doesn't pop back up later.

Closes #5292.

lib/assert.js
test/simple/test-assert.js

index 078efe39c776e4869fef78ab80e63e1f213859b0..8b6b49ae43ba41ce5f554312e467267b445bdec4 100644 (file)
@@ -38,13 +38,12 @@ var assert = module.exports = ok;
 //                             expected: expected })
 
 assert.AssertionError = function AssertionError(options) {
-  this.message = options.message;
+  this.name = 'AssertionError';
   this.actual = options.actual;
   this.expected = options.expected;
   this.operator = options.operator;
+  this.message = options.message || getMessage(this)
   var stackStartFunction = options.stackStartFunction || fail;
-
-  this.name = getName(this, options.message);
   Error.captureStackTrace(this, stackStartFunction);
 };
 
@@ -72,15 +71,10 @@ function truncate(s, n) {
   }
 }
 
-function getName(self, message) {
-  if (message) {
-    return 'AssertionError: ' + message;
-  } else {
-    return 'AssertionError: ' +
-           truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
-           self.operator + ' ' +
-           truncate(JSON.stringify(self.expected, replacer), 128);
-  }
+function getMessage(self) {
+  return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
+         self.operator + ' ' +
+         truncate(JSON.stringify(self.expected, replacer), 128);
 }
 
 // At present only the three keys mentioned above are used and
index 081eb76b653b344178685e67bcb15455e59d8433..2885858cf44fbccad558f49ed3703f8b4075f6de 100644 (file)
@@ -293,3 +293,16 @@ try {
   assert.equal(e.message, 'Missing expected exception..');
 }
 assert.ok(threw);
+
+// #5292
+try {
+  assert.equal(1, 2);
+} catch (e) {
+  assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2')
+}
+
+try {
+  assert.equal(1, 2, 'oh no');
+} catch (e) {
+  assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no')
+}