Browse Source

Improve assert error messages

1. actual and expected should be displayed in the same order they were given

2. long values should be truncated.
v0.7.4-release
Ryan Dahl 13 years ago
parent
commit
0696e78d64
  1. 45
      lib/assert.js
  2. 2
      test/simple/test-assert.js

45
lib/assert.js

@ -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(' ');
}
};

2
test/simple/test-assert.js

@ -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"');

Loading…
Cancel
Save