From 6f9ff2f49ac6ba001f96bbe83336b0b5b83724f8 Mon Sep 17 00:00:00 2001 From: DomenicDenicola Date: Tue, 1 Nov 2011 18:49:49 -0400 Subject: [PATCH] Allow objects with no prototype to tested against object literals. I often use objects created with `Object.create(null)` as dictionaries, since then they don't have pre-filled dictionary entries for e.g. `constructor`, `hasOwnProperty`, `isPrototypeOf`, etc. However, in my tests, it is quite useful to test the dictionaries I create against object literals (which have `Object.prototype` as their prototype). This patch makes an exemption to the rule that two objects must have the same constructor, for the case where one has `null` prototype and the other `Object.prototype` as its prototype. --- qunit/qunit.js | 12 +++++++++++- test/same.js | 11 +++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/qunit/qunit.js b/qunit/qunit.js index d630c43..9aeaf99 100644 --- a/qunit/qunit.js +++ b/qunit/qunit.js @@ -1065,6 +1065,10 @@ QUnit.equiv = function () { } } + var getProto = Object.getPrototypeOf || function (obj) { + return obj.__proto__; + }; + var callbacks = function () { // for string, boolean, number and null @@ -1154,7 +1158,13 @@ QUnit.equiv = function () { // comparing constructors is more strict than using // instanceof if (a.constructor !== b.constructor) { - return false; + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if (!((getProto(a) === null && getProto(b) === Object.prototype) || + (getProto(b) === null && getProto(a) === Object.prototype))) + { + return false; + } } // stack constructor before traversing properties diff --git a/test/same.js b/test/same.js index fa7e3eb..3783275 100644 --- a/test/same.js +++ b/test/same.js @@ -136,6 +136,17 @@ test("Objects Basics.", function() { a: [{ bat: undefined }] } ), false); + + // Objects with no prototype, created via Object.create(null), are used e.g. as dictionaries. + // Being able to test equivalence against object literals is quite useful. + if (Object.create) { + equals(QUnit.equiv(Object.create(null), {}), true, "empty object with no prototype VS empty object"); + + var nonEmptyWithNoProto = Object.create(null); + nonEmptyWithNoProto.foo = "bar"; + + equals(QUnit.equiv(nonEmptyWithNoProto, { foo: "bar" }), true, "nonempty object with no prototype VS empty object"); + } }); -- 2.11.0