46

I have a question regarding Chai library for unit tests. I noticed a statement saying:

  • equal: Asserts that the target is strictly (===) equal to the given value.
  • eql: Asserts that the target is deeply equal to value.

I'm confused about what the difference is between strictly and deeply.

James Risner
  • 5,451
  • 11
  • 25
  • 47
chanwcom
  • 4,420
  • 8
  • 37
  • 49

2 Answers2

48

Strictly equal (or ===) means that your are comparing exactly the same object to itself:

var myObj = {
   testProperty: 'testValue'
};
var anotherReference = myObj;

expect(myObj).to.equal(anotherReference); // The same object, only referenced by another variable
expect(myObj).to.not.equal({testProperty: 'testValue'}); // Even though it has the same property and value, it is not exactly the same object

Deeply Equal on the other hand means that every property of the compared objects (and possible deep linked objects) have the same value. So:

var myObject = {
    testProperty: 'testValue',
    deepObj: {
        deepTestProperty: 'deepTestValue'
    }
}
var anotherObject = {
    testProperty: 'testValue',
    deepObj: {
        deepTestProperty: 'deepTestValue'
    }
}
var myOtherReference = myObject;

expect(myObject).to.eql(anotherObject); // is true as all properties are the same, even the inner object (deep) one
expect(myObject).to.eql(myOtherReference) // is still also true for the same reason
David Losert
  • 4,652
  • 1
  • 25
  • 31
0

here

  1. equal is === checks if both object references or points to the exact same or identical object.

    var obj = { k1: 'v1' };

    var obj1 = obj var obj2 = obj here obj1 === obj2 (true) and obj1 == obj2 (true)

eql: Asserts that the target is deeply equal to value. number 2 ie. eql checks if both objects have the same value. (they could be different objects with the same values )

var obj1 = {
   k1: 'v1'
}

var obj2 = {
   k1: 'v1'
};

There are a few plugins that help you in terms of the above condition where you can simply use _.isEqual to check the object values:

UnderScore Lodash isDeepStrictEqual(object1, object2) Node eg console.log(_.isEqual(obj1, obj2)); // true

Aseem Jain
  • 333
  • 2
  • 7