Chai.js:对象包含/包含

时间:2013-02-28 20:21:58

标签: javascript arrays object tdd chai

Chaiinclude方法。我想测试一个对象是否包含另一个对象。例如:

var origin = {
  name: "John",
  otherObj: {
    title: "Example"
  }
}

我想用Chai来测试这个对象是否包含以下内容(它确实如此)

var match = {
  otherObj: {
    title: "Example"
  }
}

这样做似乎不起作用:

origin.should.include(match)

5 个答案:

答案 0 :(得分:21)

Hei,刚刚出版了chai-subset。看看这个:https://www.npmjs.org/package/chai-subset 这应该适合你)

 var chai = require('chai');
 var chaiSubset = require('chai-subset');
 chai.use(chaiSubset);

 var obj = {
     a: 'b',
     c: 'd',
     e: {
         foo: 'bar',
         baz: {
             qux: 'quux'
         }
     }
 };

 expect(obj).to.containSubset({
     e: {
         foo: 'bar',
         baz: {
             qux: 'quux'
         }
     }
 });

答案 1 :(得分:13)

  

include和contains断言可用作基于属性的语言链作为断言在数组中包含对象的方法字符串中的子字符串。当用作语言链时,它们切换键断言的包含标志。 [强调我的]

因此,如果您在对象(不是数组或字符串)上调用include,那么它仅用于切换键断言的contains标志。通过你的例子的外观,测试深度相等会更有意义,可能首先检查密钥。

origins.should.include.keys("otherObj");
origins.otherObj.should.deep.equal(match.otherObj);

实际上,现在我浏览其他例子,你可能会对此最开心:

origins.should.have.deep.property("otherObj", match.otherObj)

答案 2 :(得分:1)

例如在chai 4.2.0中,您可以使用深度包含

chaijs doc示例:

// Target array deeply (but not strictly) includes `{a: 1}`
expect([{a: 1}]).to.deep.include({a: 1});
expect([{a: 1}]).to.not.include({a: 1});

// Target object deeply (but not strictly) includes `x: {a: 1}`
expect({x: {a: 1}}).to.deep.include({x: {a: 1}});
expect({x: {a: 1}}).to.not.include({x: {a: 1}});

答案 3 :(得分:0)

如果知道子对象的级别,则可以简单地使用:

expect(origin.otherObj).to.include(match.otherObj);

https://www.chaijs.com/api/bdd/

答案 4 :(得分:-1)

在Chai 1.5.0中你会找到方便的方法

includeDeepMembers

http://chaijs.com/releases/

相关问题