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


91

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

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

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

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

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

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

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

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

Answers:


158

为什么数组不比较其他值的方式(例如1 == 1)

数字,字符串,布尔值,nullundefined是值,并且可以按预期进行比较。 1 == 1'a' == 'a'等等。之间的差=====在值的情况是,==将试图首先执行类型转换,这是为什么'1' == 1,但 '1' === 1

另一方面,数组是对象。=====在这种情况下,不意味着该操作数在语义上相等,但它们指的是同一个对象

assert.equal和assert.deepEqual有什么区别?

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

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

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!

4
很好的解释deepEqual(); 在进行比较之前,您并不是真正想比较的东西。
brandonscript
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.