From afcc74e7c7b46b4455338d5602b50cceddd40569 Mon Sep 17 00:00:00 2001 From: Andrey Lushnikov Date: Thu, 15 Mar 2018 11:49:53 -0700 Subject: [PATCH] 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. --- utils/testrunner/Matchers.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/utils/testrunner/Matchers.js b/utils/testrunner/Matchers.js index a58ddcf3..b46167ef 100644 --- a/utils/testrunner/Matchers.js +++ b/utils/testrunner/Matchers.js @@ -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); +}