diff --git a/src/diff.js b/src/diff.js index 67b7f48..edd8038 100644 --- a/src/diff.js +++ b/src/diff.js @@ -195,13 +195,20 @@ export function compare(input, expect) { if (Array.isArray(expect)) return arrays(input, expect); if (expect instanceof RegExp) return chars(''+input, ''+expect); + let isA = input && typeof input == 'object'; + let isB = expect && typeof expect == 'object'; + + if (isA && isB) input = sort(input, expect); + if (isB) expect = stringify(expect); + if (isA) input = stringify(input); + if (expect && typeof expect == 'object') { input = stringify(sort(input, expect)); expect = stringify(expect); } - let isA = typeof input == 'string'; - let isB = typeof expect == 'string'; + isA = typeof input == 'string'; + isB = typeof expect == 'string'; if (isA && /\r?\n/.test(input)) return lines(input, ''+expect); if (isB && /\r?\n/.test(expect)) return lines(''+input, expect); diff --git a/test/diff.js b/test/diff.js index cfad843..7dd8c22 100644 --- a/test/diff.js +++ b/test/diff.js @@ -923,6 +923,50 @@ compare('should handle multi-line string against non-type mismatch', () => { ); }); +compare('should handle `null` vs object', () => { + assert.snapshot( + strip($.compare(null, { foo: 123 })), + 'Actual:\n' + + '--null\n' + + 'Expected:\n' + + '++{\n' + + '++··"foo":·123\n' + + '++}\n' + ); + + assert.snapshot( + strip($.compare({ foo: 123 }, null)), + 'Actual:\n' + + '--{\n' + + '--··"foo":·123\n' + + '--}\n' + + 'Expected:\n' + + '++null\n' + ); +}); + +compare('should handle `undefined` vs object', () => { + assert.snapshot( + strip($.compare(undefined, { foo: 123 })), + 'Actual:\n' + + '--undefined\n' + + 'Expected:\n' + + '++{\n' + + '++··"foo":·123\n' + + '++}\n' + ); + + assert.snapshot( + strip($.compare({ foo: 123 }, undefined)), + 'Actual:\n' + + '--{\n' + + '--··"foo":·123\n' + + '--}\n' + + 'Expected:\n' + + '++undefined\n' + ); +}); + compare.run(); // ---