首页 文章

chai测试数组相等不能按预期工作

提问于
浏览
208

为什么以下失败?

expect([0,0]).to.equal([0,0]);

什么是测试的正确方法?

4 回答

  • 325

    对于 expect.equal 将比较对象而不是数据,在您的情况下,它是两个不同的数组 .

    使用 .eql 以深入比较值 . 看看这个link .
    或者你可以使用 .deep.equal 来模拟 .eql .
    或者在您的情况下,您可能想要check .members .

    对于 asserts ,您可以使用 .deepEquallink .

  • 55

    尝试使用深度等于 . 它将比较嵌套数组和嵌套Json .

    expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
    

    请参阅main documentation site .

  • 0

    此外,当数据完全相同时, to.eql 将避免由 to.eq 引起的深度相等错误,例如断言如下:

    AssertionError: expected { Object (_thing, id) } to equal { Object (_thing, id) }

  • 1

    这是如何使用chai深度测试关联数组 .

    我有一个问题试图断言两个关联数组是相等的 . 我知道这些不应该在javascript中使用,但我正在编写遗留代码的单元测试,它返回对关联数组的引用 . :-)

    我通过在函数调用之前将变量定义为对象(而不是数组)来做到这一点:

    var myAssocArray = {};   // not []
    var expectedAssocArray = {};  // not []
    
    expectedAssocArray['myKey'] = 'something';
    expectedAssocArray['differentKey'] = 'something else';
    
    // legacy function which returns associate array reference
    myFunction(myAssocArray);
    
    assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');
    

相关问题