【问题标题】:The difference between assert.equal and assert.deepEqual in Javascript testing with Mocha?用 Mocha 进行 Javascript 测试中 assert.equal 和 assert.deepEqual 的区别?
【发布时间】:2012-10-24 21:15:05
【问题描述】:

我正在使用 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 命令行,我仍然得到错误。

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

【问题讨论】:

    标签: javascript arrays testing mocha.js


    【解决方案1】:

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

    数字、字符串、布尔值、nullundefined 是值,并且按照您的预期进行比较。 1 == 1'a' == 'a' 等等。 ===== 在值的情况下的区别在于 == 将首先尝试执行类型转换,这就是为什么 '1' == 1 '1' === 1

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

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

    assert.equal 的行为如上所述。如果参数是!=,它实际上会失败,如您所见in the source。因此,对于您的数字字符串数组,它会失败,因为尽管它们本质上是等价的,但它们不是同一个对象。

    另一方面,深层(又名结构)相等并不测试操作数是否是同一个对象,而是测试它们是否等价。从某种意义上说,您可以说它强制将对象作为值进行比较。

    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!
    

    【讨论】:

    • 很好的解释deepEqual();在您真正遇到它之前,您在比较中并不是真正想到的东西。
    猜你喜欢
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多