test: fix Matcher.toEqual to not depend on key insertion order (#2091)

Objects `{foo: 1, bar: 2}` and `{bar: 2, foo: 1}` should be considered
equal.
This commit is contained in:
Andrey Lushnikov 2018-03-15 11:49:53 -07:00 committed by GitHub
parent 4b7fbf8ee0
commit afcc74e7c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -96,8 +96,10 @@ const DefaultMatchers = {
},
toEqual: function(value, other, message) {
message = message || `${JSON.stringify(value)}${JSON.stringify(other)}`;
return { pass: JSON.stringify(value) === JSON.stringify(other), message };
const valueJson = stringify(value);
const otherJson = stringify(other);
message = message || `${valueJson}${otherJson}`;
return { pass: valueJson === otherJson, message };
},
toBeCloseTo: function(value, other, precision, message) {
@ -107,3 +109,16 @@ const DefaultMatchers = {
};
}
};
function stringify(value) {
function stabilize(key, object) {
if (typeof object !== 'object' || object === undefined || object === null)
return object;
const result = {};
for (const key of Object.keys(object).sort())
result[key] = object[key];
return result;
}
return JSON.stringify(stabilize(null, value), stabilize);
}