Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(diff): handle various types combination in "compare" #62

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions src/diff.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,28 @@ export function stringify(input) {
}

export function compare(input, expect) {
if (Array.isArray(expect)) return arrays(input, expect);
if (expect instanceof RegExp) return chars(''+input, ''+expect);
if (Array.isArray(expect) && Array.isArray(input)) return arrays(input, expect);
if (expect instanceof RegExp) {
try {
return chars(''+input, ''+expect);
} catch (e) {
if (e.message !== 'Cannot convert object to primitive value') {
throw e
}
}
}

if (expect && typeof expect == 'object') {
input = stringify(sort(input, expect));
let inputIsObject = input && typeof input === 'object'
let expectIsObject = expect && typeof expect == 'object'
if (expectIsObject && inputIsObject) {
input = sort(input, expect);
}
if (expectIsObject) {
expect = stringify(expect);
}
if (inputIsObject) {
input = stringify(input);
}

let isA = typeof input == 'string';
let isB = typeof expect == 'string';
Expand Down
29 changes: 29 additions & 0 deletions test/diff.js
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,35 @@ compare('should handle multi-line string against non-type mismatch', () => {
);
});

compare('should not fail when comparing different types', () => {
const values = [
true,
false,
null,
undefined,
{foo: 'bar'},
[],
new Date(),
'str',
1,
NaN,
Infinity,
/abc/,
function () {},
new Promise(() => {}),
$,
];
for (const val1 of values) {
for (const val2 of values) {
let aType = Object.prototype.toString.call(val1)
aType = aType.substring(8, aType.length - 1)
let bType = Object.prototype.toString.call(val2)
bType = bType.substring(8, bType.length - 1)
assert.not.throws(() => $.compare(val1, val2), `${aType} is not comparable to ${bType}`)
}
}
});

compare.run();

// ---
Expand Down