☕️ Classic, reliable, trusted test framework for Node.js and the browser
improve diff behavior
Christopher Hiller7a41fc25da86
diff --git a/lib/utils.js b/lib/utils.jsindex d8ec405c..c6243750 100644--- a/lib/utils.js+++ b/lib/utils.js@@ -292,18 +292,100 @@ exports.highlightTags = function(name) {}};+/**+ * If a value could have properties, and has none, this function is called, which returns+ * a string representation of the empty value.+ *+ * Functions w/ no properties return `'[Function]'`+ * Arrays w/ length === 0 return `'[]'`+ * Objects w/ no properties return `'{}'`+ * All else: return result of `value.toString()`+ *+ * @param {*} value Value to inspect+ * @param {string} [type] The type of the value, if known.+ * @returns {string}+ */+var emptyRepresentation = function emptyRepresentation(value, type) {+ type = type || exports.type(value);++ switch(type) {+ case 'function':+ return '[Function]';+ case 'object':+ return '{}';+ case 'array':+ return '[]';+ default:+ return value.toString();+ }+};++/**+ * Takes some variable and asks `{}.toString()` what it thinks it is.+ * @param {*} value Anything+ * @example+ * type({}) // 'object'+ * type([]) // 'array'+ * type(1) // 'number'+ * type(false) // 'boolean'+ * type(Infinity) // 'number'+ * type(null) // 'null'+ * type(new Date()) // 'date'+ * type(/foo/) // 'regexp'+ * type('type') // 'string'+ * type(global) // 'global'+ * @api private+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString+ * @returns {string}+ */+exports.type = function type(value) {+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {+ return 'buffer';+ }+ return Object.prototype.toString.call(value)+ .replace(/^\[.+\s(.+?)\]$/, '$1')+ .toLowerCase();+};/**- * Stringify `obj`.+ * @summary Stringify `value`.+ * @description Different behavior depending on type of value.+ * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.+ * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.+ * - If `value` is an *empty* object, function, or array, return result of function+ * {@link emptyRepresentation}.+ * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of+ * JSON.stringify().*- * @param {Object} obj- * @return {String}+ * @see exports.type+ * @param {*} value+ * @return {string}* @api private*/-exports.stringify = function(obj) {- if (obj instanceof RegExp) return obj.toString();- return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1');+exports.stringify = function(value) {+ var prop,+ type = exports.type(value);++ if (type === 'null' || type === 'undefined') {+ return '[' + type + ']';+ }++ if (type === 'date') {+ return '[Date: ' + value.toISOString() + ']';+ }++ if (!~exports.indexOf(['object', 'array', 'function'], type)) {+ return value.toString();+ }++ for (prop in value) {+ if (value.hasOwnProperty(prop)) {+ return JSON.stringify(exports.canonicalize(value), null, 2).replace(/,(\n|$)/g, '$1');+ }+ }++ return emptyRepresentation(value, type);};/**@@ -313,45 +395,89 @@ exports.stringify = function(obj) {* @api private*/exports.isBuffer = function (arg) {- return typeof Buffer !== 'undefined' && arg instanceof Buffer;+ return typeof Buffer !== 'undefined' && Buffer.isBuffer(arg);};/**- * Return a new object that has the keys in sorted order.- * @param {Object} obj- * @param {Array} [stack]- * @return {Object}+ * @summary Return a new Thing that has the keys in sorted order. Recursive.+ * @description If the Thing...+ * - has already been seen, return string `'[Circular]'`+ * - is `undefined`, return string `'[undefined]'`+ * - is `null`, return value `null`+ * - is some other primitive, return the value+ * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method+ * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.+ * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`+ *+ * @param {*} value Thing to inspect. May or may not have properties.+ * @param {Array} [stack=[]] Stack of seen values+ * @return {(Object|Array|Function|string|undefined)}+ * @see {@link exports.stringify}* @api private*/-exports.canonicalize = function(obj, stack) {- stack = stack || [];+exports.canonicalize = function(value, stack) {+ var canonicalizedObj,+ type = exports.type(value),+ prop,+ withStack = function withStack(value, fn) {+ stack.push(value);+ fn();+ stack.pop();+ };- if (exports.indexOf(stack, obj) !== -1) return '[Circular]';+ stack = stack || [];- var canonicalizedObj;+ if (exports.indexOf(stack, value) !== -1) {+ return '[Circular]';+ }- if(exports.isBuffer(obj)) {- return obj;- } else if ({}.toString.call(obj) === '[object Array]') {- stack.push(obj);- canonicalizedObj = exports.map(obj, function (item) {- return exports.canonicalize(item, stack);- });- stack.pop();- } else if (typeof obj === 'object' && obj !== null) {- stack.push(obj);- canonicalizedObj = {};- exports.forEach(exports.keys(obj).sort(), function (key) {- canonicalizedObj[key] = exports.canonicalize(obj[key], stack);- });- stack.pop();- } else {- canonicalizedObj = obj;+ switch(type) {+ case 'undefined':+ canonicalizedObj = '[undefined]';+ break;+ case 'buffer':+ case 'null':+ canonicalizedObj = value;+ break;+ case 'array':+ withStack(value, function () {+ canonicalizedObj = exports.map(value, function (item) {+ return exports.canonicalize(item, stack);+ });+ });+ break;+ case 'date':+ canonicalizedObj = '[Date: ' + value.toISOString() + ']';+ break;+ case 'function':+ for (prop in value) {+ canonicalizedObj = {};+ break;+ }+ if (!canonicalizedObj) {+ canonicalizedObj = emptyRepresentation(value, type);+ break;+ }+ /* falls through */+ case 'object':+ canonicalizedObj = canonicalizedObj || {};+ withStack(value, function () {+ exports.forEach(exports.keys(value).sort(), function (key) {+ canonicalizedObj[key] = exports.canonicalize(value[key], stack);+ });+ });+ break;+ case 'number':+ case 'boolean':+ canonicalizedObj = value;+ break;+ default:+ canonicalizedObj = value.toString();}return canonicalizedObj;- };+};/*** Lookup file names at the given `path`.diff --git a/mocha.js b/mocha.jsindex 564a4f31..e20bf074 100644--- a/mocha.js+++ b/mocha.js@@ -4178,7 +4178,8 @@ require.register("runnable.js", function(module, exports, require){var EventEmitter = require('browser/events').EventEmitter, debug = require('browser/debug')('mocha:runnable')- , milliseconds = require('./ms');+ , milliseconds = require('./ms')+ , utils = require('./utils');/*** Save timer references to avoid Sinon interfering (see GH-237).@@ -4404,7 +4405,7 @@ Runnable.prototype.run = function(fn){done();});} catch (err) {- done(err);+ done(utils.getError(err));}return;}@@ -4421,7 +4422,7 @@ Runnable.prototype.run = function(fn){callFn(this.fn);}} catch (err) {- done(err);+ done(utils.getError(err));}function callFn(fn) {@@ -4465,7 +4466,9 @@ var globals = ['setInterval','clearInterval','XMLHttpRequest',- 'Date'+ 'Date',+ 'setImmediate',+ 'clearImmediate'];/**@@ -4694,7 +4697,6 @@ Runner.prototype.hook = function(name, fn){function next(i) {var hook = hooks[i];if (!hook) return fn();- if (self.failures && suite.bail()) return fn();self.currentRunnable = hook;hook.ctx.currentTest = self.test;@@ -4988,7 +4990,7 @@ Runner.prototype.uncaught = function(err){}.call(err) ? err : ( err.message || err ));} else {debug('uncaught undefined exception');- err = new Error('Caught undefined error, did you throw without specifying what?');+ err = utils.undefinedError();}err.uncaught = true;@@ -5811,54 +5813,187 @@ exports.highlightTags = function(name) {}};+/**+ * If a value could have properties, and has none, this function is called, which returns+ * a string representation of the empty value.+ *+ * Functions w/ no properties return `'[Function]'`+ * Arrays w/ length === 0 return `'[]'`+ * Objects w/ no properties return `'{}'`+ * All else: return result of `value.toString()`+ *+ * @param {*} value Value to inspect+ * @param {string} [type] The type of the value, if known.+ * @returns {string}+ */+var emptyRepresentation = function emptyRepresentation(value, type) {+ type = type || exports.type(value);++ switch(type) {+ case 'function':+ return '[Function]';+ case 'object':+ return '{}';+ case 'array':+ return '[]';+ default:+ return value.toString();+ }+};++/**+ * Takes some variable and asks `{}.toString()` what it thinks it is.+ * @param {*} value Anything+ * @example+ * type({}) // 'object'+ * type([]) // 'array'+ * type(1) // 'number'+ * type(false) // 'boolean'+ * type(Infinity) // 'number'+ * type(null) // 'null'+ * type(new Date()) // 'date'+ * type(/foo/) // 'regexp'+ * type('type') // 'string'+ * type(global) // 'global'+ * @api private+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString+ * @returns {string}+ */+exports.type = function type(value) {+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {+ return 'buffer';+ }+ return Object.prototype.toString.call(value)+ .replace(/^\[.+\s(.+?)\]$/, '$1')+ .toLowerCase();+};/**- * Stringify `obj`.+ * @summary Stringify `value`.+ * @description Different behavior depending on type of value.+ * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.+ * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.+ * - If `value` is an *empty* object, function, or array, return result of function+ * {@link emptyRepresentation}.+ * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of+ * JSON.stringify().*- * @param {Object} obj- * @return {String}+ * @see exports.type+ * @param {*} value+ * @return {string}* @api private*/-exports.stringify = function(obj) {- if (obj instanceof RegExp) return obj.toString();- return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1');+exports.stringify = function(value) {+ var prop,+ type = exports.type(value);++ if (type === 'null' || type === 'undefined') {+ return '[' + type + ']';+ }+ if (!~exports.indexOf(['object', 'array', 'function', 'date'], type)) {+ return value.toString();+ }++ for (prop in value) {+ if (value.hasOwnProperty(prop)) {+ return JSON.stringify(exports.canonicalize(value), null, 2).replace(/,(\n|$)/g, '$1');+ }+ }++ return emptyRepresentation(value, type);};/**- * Return a new object that has the keys in sorted order.- * @param {Object} obj- * @param {Array} [stack]- * @return {Object}+ * Return if obj is a Buffer+ * @param {Object} arg+ * @return {Boolean}* @api private*/+exports.isBuffer = function (arg) {+ return typeof Buffer !== 'undefined' && Buffer.isBuffer(arg);+};-exports.canonicalize = function(obj, stack) {- stack = stack || [];+/**+ * @summary Return a new Thing that has the keys in sorted order. Recursive.+ * @description If the Thing...+ * - has already been seen, return string `'[Circular]'`+ * - is `undefined`, return string `'[undefined]'`+ * - is `null`, return value `null`+ * - is some other primitive, return the value+ * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method+ * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.+ * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`+ *+ * @param {*} value Thing to inspect. May or may not have properties.+ * @param {Array} [stack=[]] Stack of seen values+ * @return {(Object|Array|Function|string|undefined)}+ * @see {@link exports.stringify}+ * @api private+ */- if (exports.indexOf(stack, obj) !== -1) return '[Circular]';+exports.canonicalize = function(value, stack) {+ var canonicalizedObj,+ type = exports.type(value),+ prop,+ withStack = function withStack(value, fn) {+ stack.push(value);+ fn();+ stack.pop();+ };- var canonicalizedObj;+ stack = stack || [];- if ({}.toString.call(obj) === '[object Array]') {- stack.push(obj);- canonicalizedObj = exports.map(obj, function (item) {- return exports.canonicalize(item, stack);- });- stack.pop();- } else if (typeof obj === 'object' && obj !== null) {- stack.push(obj);- canonicalizedObj = {};- exports.forEach(exports.keys(obj).sort(), function (key) {- canonicalizedObj[key] = exports.canonicalize(obj[key], stack);- });- stack.pop();- } else {- canonicalizedObj = obj;+ if (exports.indexOf(stack, value) !== -1) {+ return '[Circular]';+ }++ switch(type) {+ case 'undefined':+ canonicalizedObj = '[undefined]';+ break;+ case 'buffer':+ case 'null':+ canonicalizedObj = value;+ break;+ case 'array':+ withStack(value, function () {+ canonicalizedObj = exports.map(value, function (item) {+ return exports.canonicalize(item, stack);+ });+ });+ break;+ case 'date':+ canonicalizedObj = '[Date: ' + value.toISOString() + ']';+ break;+ case 'function':+ for (prop in value) {+ canonicalizedObj = {};+ break;+ }+ if (!canonicalizedObj) {+ canonicalizedObj = emptyRepresentation(value, type);+ break;+ }+ /* falls through */+ case 'object':+ canonicalizedObj = canonicalizedObj || {};+ withStack(value, function () {+ exports.forEach(exports.keys(value).sort(), function (key) {+ canonicalizedObj[key] = exports.canonicalize(value[key], stack);+ });+ });+ break;+ case 'number':+ case 'boolean':+ canonicalizedObj = value;+ break;+ default:+ canonicalizedObj = value.toString();}return canonicalizedObj;- };+};/*** Lookup file names at the given `path`.@@ -5906,6 +6041,28 @@ exports.lookupFiles = function lookupFiles(path, extensions, recursive) {return files;};+/**+ * Generate an undefined error with a message warning the user.+ *+ * @return {Error}+ */++exports.undefinedError = function(){+ return new Error('Caught undefined error, did you throw without specifying what?');+};++/**+ * Generate an undefined error if `err` is not defined.+ *+ * @param {Error} err+ * @return {Error}+ */++exports.getError = function(err){+ return err || exports.undefinedError();+};++}); // module: utils.js// The global object is "self" in Web Workers.var global = (function() { return this; })();diff --git a/test/acceptance/utils.js b/test/acceptance/utils.jsindex 77817d2e..8c554c12 100644--- a/test/acceptance/utils.js+++ b/test/acceptance/utils.js@@ -72,18 +72,161 @@ describe('lib/utils', function () {});describe('stringify', function(){- it('should canoncalize the object', function(){++ var stringify = utils.stringify;++ it('should canonicalize the object', function(){var travis = { name: 'travis', age: 24 };var travis2 = { age: 24, name: 'travis' };- utils.stringify(travis).should.equal(utils.stringify(travis2));+ stringify(travis).should.equal(stringify(travis2));});- it('should handle circular structures', function(){+ it('should handle circular structures in objects', function(){var travis = { name: 'travis' };travis.whoami = travis;- utils.stringify(travis).should.equal('{\n "name": "travis"\n "whoami": "[Circular]"\n}');+ stringify(travis).should.equal('{\n "name": "travis"\n "whoami": "[Circular]"\n}');+ });++ it('should handle circular structures in arrays', function(){+ var travis = ['travis'];+ travis.push(travis);++ stringify(travis).should.equal('[\n "travis"\n "[Circular]"\n]');+ });++ it('should handle circular structures in functions', function(){+ var travis = function () {};+ travis.fn = travis;++ stringify(travis).should.equal('{\n "fn": "[Circular]"\n}');+ });+++ it('should handle various non-undefined, non-null, non-object, non-array, non-date, and non-function values', function () {+ var regexp = new RegExp("(?:)"),+ regExpObj = { regexp: regexp },+ regexpString = '/(?:)/';++ stringify(regExpObj).should.equal('{\n "regexp": "' + regexpString + '"\n}');+ stringify(regexp).should.equal(regexpString);++ var number = 1,+ numberObj = { number: number },+ numberString = '1';++ stringify(numberObj).should.equal('{\n "number": ' + number + '\n}');+ stringify(number).should.equal(numberString);++ var boolean = false,+ booleanObj = { boolean: boolean },+ booleanString = 'false';++ stringify(booleanObj).should.equal('{\n "boolean": ' + boolean + '\n}');+ stringify(boolean).should.equal(booleanString);++ var string = 'sneepy',+ stringObj = { string: string };++ stringify(stringObj).should.equal('{\n "string": "' + string + '"\n}');+ stringify(string).should.equal(string);++ var nullValue = null,+ nullObj = { 'null': null },+ nullString = '[null]';++ stringify(nullObj).should.equal('{\n "null": null\n}');+ stringify(nullValue).should.equal(nullString);++ });++ it('should handle arrays', function () {+ var array = ['dave', 'dave', 'dave', 'dave'],+ arrayObj = {array: array},+ arrayString = array.map(function () {+ return ' "dave"';+ }).join('\n');++ stringify(arrayObj).should.equal('{\n "array": [\n' + arrayString + '\n ]\n}');+ stringify(array).should.equal('[' + arrayString.replace(/\s+/g, '\n ') + '\n]');+ });++ it('should handle functions', function () {+ var fn = function() {},+ fnObj = {fn: fn},+ fnString = '[Function]';++ stringify(fnObj).should.equal('{\n "fn": "' + fnString + '"\n}');+ stringify(fn).should.equal('[Function]');+ });++ it('should handle empty objects', function () {+ stringify({}).should.equal('{}');+ stringify({foo: {}}).should.equal('{\n "foo": {}\n}');+ });++ it('should handle empty arrays', function () {+ stringify([]).should.equal('[]');+ stringify({foo: []}).should.equal('{\n "foo": []\n}');+ });++ it('should handle non-empty arrays', function () {+ stringify(['a', 'b', 'c']).should.equal('[\n "a"\n "b"\n "c"\n]')+ });++ it('should handle empty functions (with no properties)', function () {+ stringify(function(){}).should.equal('[Function]');+ stringify({foo: function() {}}).should.equal('{\n "foo": "[Function]"\n}');+ stringify({foo: function() {}, bar: 'baz'}).should.equal('{\n "bar": "baz"\n "foo": "[Function]"\n}');+ });++ it('should handle functions w/ properties', function () {+ var fn = function(){};+ fn.bar = 'baz';+ stringify(fn).should.equal('{\n "bar": "baz"\n}');+ stringify({foo: fn}).should.equal('{\n "foo": {\n "bar": "baz"\n }\n}');+ });++ it('should handle undefined values', function () {+ stringify({foo: undefined}).should.equal('{\n "foo": "[undefined]"\n}');+ stringify({foo: 'bar', baz: undefined}).should.equal('{\n "baz": "[undefined]"\n "foo": "bar"\n}');+ stringify().should.equal('[undefined]');+ });++ it('should recurse', function () {+stringify({foo: {bar: {baz: {quux: {herp: 'derp'}}}}}).should.equal('{\n "foo": {\n "bar": {\n "baz": {\n "quux": {\n "herp": "derp"\n }\n }\n }\n }\n}');+ });++ it('might get confusing', function () {+ stringify(null).should.equal(stringify('[null]'));+ });++ it('should not freak out if it sees a primitive twice', function () {+ stringify({foo: null, bar: null}).should.equal('{\n "bar": null\n "foo": null\n}');+ stringify({foo: 1, bar: 1}).should.equal('{\n "bar": 1\n "foo": 1\n}');+ });++ it.only('should stringify dates', function () {+ var date = new Date(0);+ stringify(date).should.equal('[Date: 1970-01-01T00:00:00.000Z]');+ stringify({date: date}).should.equal('{\n "date": "[Date: 1970-01-01T00:00:00.000Z]"\n}');+ });+ });++ describe('type', function () {+ var type = utils.type;+ it('should recognize various types', function () {+ type({}).should.equal('object');+ type([]).should.equal('array');+ type(1).should.equal('number');+ type(Infinity).should.equal('number');+ type(null).should.equal('null');+ type(new Date()).should.equal('date');+ type(/foo/).should.equal('regexp');+ type('type').should.equal('string');+ type(global).should.equal('global');+ type(true).should.equal('boolean');});});