关于数组:使用Mocha进行Javascript测试时assert.equal和assert.deepEqual之间的区别?

The difference between assert.equal and assert.deepEqual in Javascript testing with Mocha?

我正在使用Mocha在Express.js应用程序中测试一个小模块。 在此模块中,我的函数之一返回一个数组。 我想测试数组对于给定的输入是否正确。 我这样做是这样的:

1
2
3
4
5
6
suite('getWords', function(){
    test("getWords should return list of numbers", function() {
        var result = ['555', '867', '5309'];
        assert.equal(result, getWords('555-867-5309'));
    });
});

运行此命令时,出现以下断言错误:

1
AssertionError: ["555","867","5309"] == ["555","867","5309"]

但是,当我将测试更改为assert.deepEqual时,测试可以顺利通过。 我想知道是否是== vs ===的情况,但是如果我输入

1
[1,2,3] === [1,2,3]

进入node.js命令行,我仍然会得到false。

为什么数组不比较其他值的方式(例如1 == 1)? assert.equal和assert.deepEqual有什么区别?


Why do arrays not compare the way other values do (e.g. 1==1)

数字,字符串,布尔值,nullundefined是值,并且可以按预期进行比较。 1 == 1'a' == 'a'等。 在使用值的情况下,=====之间的区别在于,==将首先尝试执行类型转换,这就是为什么'1' == 1而不是'1' === 1的原因。

另一方面,数组是对象。 在这种情况下,=====并不表示操作数在语义上是相等的,而是表示它们引用相同的对象。

what is the difference between assert.equal and assert.deepEqual?

assert.equal的行为如上所述。 正如您在源代码中看到的那样,如果参数为!=,则实际上失败。 因此,它对于数字字符串数组失败,因为尽管它们本质上是等效的,但它们不是同一对象。

另一方面,深度(aka结构)相等性不测试操作数是否是同一对象,而是测试它们是否等效。 从某种意义上讲,您可以说它迫使对象进行比较,就像它们是值一样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var a = [1,2,3]  
var b = a              // As a and b both refer to the same object
a == b                 // this is true
a === b                // and this is also true

a = [1,2,3]            // here a and b have equivalent contents, but do not
b = [1,2,3]            // refer to the same Array object.
a == b                 // Thus this is false.

assert.deepEqual(a, b) // However this passes, as while a and b are not the
                       // same object, they are still arrays containing 1, 2, 3

assert.deepEqual(1, 1) // Also passes when given equal values

var X = function() {}
a = new X
b = new X
a == b                 // false, not the same object
assert.deepEqual(a, b) // pass, both are unadorned X objects
b.foo = 'bar'
assert.deepEqual(a, b) // fail!