Improvements AssertionError message
authorkoichik <koichik@improvement.jp>
Sun, 10 Jul 2011 09:47:41 +0000 (18:47 +0900)
committerkoichik <koichik@improvement.jp>
Wed, 13 Jul 2011 17:08:24 +0000 (02:08 +0900)
Fixes #217.

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

index 57a798a..9ca871d 100644 (file)
@@ -56,9 +56,21 @@ assert.AssertionError.prototype.toString = function() {
     return [this.name + ':', this.message].join(' ');
   } else {
     return [this.name + ':',
-            JSON.stringify(this.expected),
+            JSON.stringify(this.expected, replacer),
             this.operator,
-            JSON.stringify(this.actual)].join(' ');
+            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;
   }
 };
 
index f15072f..b47f045 100644 (file)
@@ -229,3 +229,34 @@ try {
 console.log('All OK');
 assert.ok(gotError);
 
+
+// #217
+function testAssertionMessage(actual, expected) {
+  try {
+    assert.equal(actual, '');
+  } catch (e) {
+    assert.equal(e.toString(),
+        ['AssertionError:', '""', '==', expected].join(' '));
+  }
+}
+testAssertionMessage(undefined, '"undefined"');
+testAssertionMessage(null, 'null');
+testAssertionMessage(true, 'true');
+testAssertionMessage(false, 'false');
+testAssertionMessage(0, '0');
+testAssertionMessage(100, '100');
+testAssertionMessage(NaN, '"NaN"');
+testAssertionMessage(Infinity, '"Infinity"');
+testAssertionMessage(-Infinity, '"-Infinity"');
+testAssertionMessage('', '""');
+testAssertionMessage('foo', '"foo"');
+testAssertionMessage([], '[]');
+testAssertionMessage([1,2,3], '[1,2,3]');
+testAssertionMessage(/a/, '"/a/"');
+testAssertionMessage(/abc/gim, '"/abc/gim"');
+testAssertionMessage(function f() {}, '"function f() {}"');
+testAssertionMessage({}, '{}');
+testAssertionMessage({a:undefined, b:null}, '{"a":"undefined","b":null}');
+testAssertionMessage({a:NaN, b:Infinity, c:-Infinity},
+    '{"a":"NaN","b":"Infinity","c":"-Infinity"}');
+