【问题标题】:nodejs deep equal with differencesnodejs 深度相等,有差异
【发布时间】:2012-11-27 09:22:01
【问题描述】:

有没有一个断言库可以告诉我两个对象在深入比较时有什么区别?

我尝试过使用 chai,但它只是告诉我对象是不同的,但不是在哪里。 节点的断言也是如此......

【问题讨论】:

  • 你使用什么测试框架?你愿意转换吗?
  • 我正在使用摩卡咖啡,我愿意改变是的。但我真的很喜欢摩卡;)
  • 我试过应该,当我比较两个不同的对象时,它只是告诉我“错误:AssertionError:预期 {....} 等于 {....}”而没有向我显示任何地方实际差异。我在 Windows 上,所以不知道它是否会以任何方式改变库的行为......
  • 我也有同样的问题,但我也没有找到解决办法。
  • 有人知道为什么会这样吗?

标签: unit-testing node.js


【解决方案1】:

是的,有:assert-diff

你可以这样使用它:

var assert = require('assert-diff')

it('diff deep equal with message', function() {
  assert.deepEqual({pow: "boom", same: true, foo: 2}, {same: true, bar: 2, pow: "bang"}, "this should fail")
})

结果:

1) diff deep equal with message:
     AssertionError: this should fail
 {
-  bar: 2
+  foo: 2
-  pow: "bang"
+  pow: "boom"
 }

【讨论】:

    【解决方案2】:

    基于this StackOverflow answer,我相信我遇到了这个问题,因为我的测试是异步的。

    通过使用以下模式,我让差异再次正常工作:

    try {
      expect(true).to.equal(false);
      done();  // success: call done with no parameter to indicate that it() is done()
    } catch(e) {
      done(e);  // failure: call done with an error Object to indicate that it() failed
    }
    

    【讨论】:

      【解决方案3】:

      使用 chai 1.5.0 和 mocha 1.8.1,以下对我有用:

      var expect = require('chai').expect;
      
      it("shows a diff of arrays", function() {
        expect([1,2,3]).to.deep.equal([1,2,3, {}]);
      });
      
      it("shows a diff of objects", function() {
        expect({foo: "bar"}).to.deep.equal({foo: "bar", baz: "bub"});
      });
      

      结果:

      ✖ 2 of 2 tests failed:
      
      1)  shows a diff of arrays:
      
        actual expected
      
        1 | [
        2 |   1,
        3 |   2,
        4 |   3,
        5 |   {}
        6 | ]
      
      2)  shows a diff of objects:
      
        actual expected
      
        {
          "foo": "bar",
          "baz": "bub"
        }
      

      此处未显示的是输出以红色/绿色突出显示,其中行意外/缺失。

      【讨论】:

        【解决方案4】:

        Substack 的 difflet 可能是你需要的

        更新:但等等,还有更多:https://github.com/andreyvit/json-diff https://github.com/algesten/jsondiff https://github.com/samsonjs/json-diff

        【讨论】:

        • 感谢您的指点,如果我只是在寻找一个完美的命令行工具。但我正在寻找在单元测试期间使用的断言函数。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        • 2014-07-18
        • 2023-03-12
        • 2016-12-20
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多