Chai Library中的equal和eql有什么区别

cha*_*com 16 javascript unit-testing chai

我对Javascript很新,我对Chai库进行单元测试有一个简单的问题.

当我在Chai库上研究一些材料时,我看到一个声明说"等于目标严格等于(===)到值"和eql"断言目标与值非常相等.".

但我对于严格和深刻的差异感到困惑.

Cha*_*ear 20

严格等于(或===)意味着您正在将完全相同的对象与自身进行比较:

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
Run Code Online (Sandbox Code Playgroud)

另一方面,深度相等意味着比较对象的每个属性(以及可能的深度链接对象)具有相同的值.所以:

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
Run Code Online (Sandbox Code Playgroud)

  • 老实说,这是一个可怕的约定。我认为应该只使用“等于”和“ deepEqual”。 (18认同)