Improve assert error messages
authorRyan Dahl <ry@tinyclouds.org>
Tue, 9 Aug 2011 21:18:16 +0000 (14:18 -0700)
committerRyan Dahl <ry@tinyclouds.org>
Tue, 9 Aug 2011 21:20:06 +0000 (14:20 -0700)
1. actual and expected should be displayed in the same order they were given

2. long values should be truncated.

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

index 9ca871da3d2235f8d04e9f93636a9d36d202681c..3f35b4510e70828782a3fc24547cd5ac019d345c 100644 (file)
@@ -51,26 +51,37 @@ assert.AssertionError = function AssertionError(options) {
 };
 util.inherits(assert.AssertionError, Error);
 
+function replacer(key, value) {
+  if (value === undefined) {
+    return '' + value;
+  }
+  if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
+    return value.toString();
+  }
+  if (typeof value === 'function' || value instanceof RegExp) {
+    return value.toString();
+  }
+  return value;
+}
+
+function truncate(s, n) {
+  if (typeof s == 'string') {
+    return s.length < n ? s : s.slice(0, n);
+  } else {
+    return s;
+  }
+}
+
 assert.AssertionError.prototype.toString = function() {
   if (this.message) {
-    return [this.name + ':', this.message].join(' ');
+    return [ this.name + ':', this.message ].join(' ');
   } else {
-    return [this.name + ':',
-            JSON.stringify(this.expected, replacer),
-            this.operator,
-            JSON.stringify(this.actual, replacer)].join(' ');
-  }
-  function replacer(key, value) {
-    if (value === undefined) {
-      return '' + value;
-    }
-    if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
-      return value.toString();
-    }
-    if (typeof value === 'function' || value instanceof RegExp) {
-      return value.toString();
-    }
-    return value;
+    return [
+      this.name + ':',
+      truncate(JSON.stringify(this.actual, replacer), 128),
+      this.operator,
+      truncate(JSON.stringify(this.expected, replacer), 128)
+    ].join(' ');
   }
 };
 
index b47f045454908e8f84d4bc71e784735f19e4a07a..f0e78b85f6a7b948f9632f535abfcd5dc12c048d 100644 (file)
@@ -236,7 +236,7 @@ function testAssertionMessage(actual, expected) {
     assert.equal(actual, '');
   } catch (e) {
     assert.equal(e.toString(),
-        ['AssertionError:', '""', '==', expected].join(' '));
+        ['AssertionError:', expected, '==', '""'].join(' '));
   }
 }
 testAssertionMessage(undefined, '"undefined"');