Let's set the scene: I have a function that returns an array of objects. These objects do not have any enumerable properties, but are sourced from a common cache or store.
In my test cases, I want to verify if the contents of the returned array are accurate. Initially, I tried using deepEqual()
for this purpose, but the tests did not produce the expected results (I've simplified the example):
QUnit.test( "array of objects", function( assert ) {
// create two objects
var o1 = new Obj( 1 ),
o2 = new Obj( 2 );
// compare objects themselves
assert.notEqual( o1, o2, 'different objects' ); // success
// compare identical arrays
assert.deepEqual( [ o1 ], [ o1 ], 'identical arrays - deepEqual' ); // success
// compare different arrays
assert.notDeepEqual( [ o1 ], [ o2 ], 'different arrays - deepEqual' ); // fail
});
// sample object constructor
function Obj(){}
(I also experimented with propEqual()
to see if it yielded different results.)
Although QUnit can differentiate between two objects (as shown in the first test), it fails to recognize the difference when dealing with arrays.
After some tinkering, I found that introducing an enumerable property where instances differ makes QUnit acknowledge the distinction: Revised Fiddle
function Obj( val ){ this._val = val; }
Coincidentally, setting the same value for this property in both instances leads to similar behavior as having no property at all (Fiddle).
With these examples in mind,
How can I prompt QUnit to compare two objects based on their identity to scrutinize an array's contents?
Following a discussion with @Ilya, here is a restatement of the actual question:
Is there a way to utilize deepEqual()
solely for one level, implying that all elements within the provided array should be compared by object identity?
PS: While comparing element by element in the array might seem like a simple solution, I'm exploring faster alternatives.