nodejs与差异深度相等

时间:2012-12-09 23:14:19

标签: unit-testing node.js

是否有一个断言库会告诉我深度比较时两个对象之间有什么区别?

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

4 个答案:

答案 0 :(得分:3)

Substack的difflet可能就是你需要的

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

答案 1 :(得分:2)

使用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"
  }

这里没有显示的是输出突出显示为红色/绿色,其中行是意外/缺失的。

答案 2 :(得分:2)

基于this StackOverflow answer,我认为问题是因为我的测试是异步的。

我使用以下模式让diffs再次正常工作:

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 :(得分:0)

是的,有: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"
 }