javascript Mocha, Chai:断言对象包含在对象数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17558518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:46:08  来源:igfitidea点击:

Mocha, Chai: Assert that Object is included in an Array of Objects

javascripttestingmochachai

提问by mck

Chai has a nice way to assert if an Array includes a certain element

Chai 有一个很好的方法来断言数组是否包含某个元素

expect([1,2,3]).to.include(2);

What I would like is something similar, given an Array of Objects:

给定一个对象数组,我想要的是类似的东西:

expect([{a:1},{b:2}]).to.include({b:2});

Is this possible?

这可能吗?

回答by Andreas K?berle

Take a look at the Chai Things plugin, that does what you want:

看看Chai Things 插件,它可以满足您的需求:

[{a:1},{b:2}].should.include.something.that.deep.equals({b:2})

回答by lfender6445

Here is an alternative and non order dependent approach for collections:

这是集合的另一种非顺序依赖方法:

array

大批

expect([1, 2, 3]).to.include.members([3, 2, 1])

You can also use this with a deepflag for comparison of objects:

您还可以将其与deep标志一起使用以比较对象:

array of objects

对象数组

expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]);

object

目的

expect({foo: 'bar', width: 190, height: 90}).to.include({ height: 90, width: 190 })

回答by Jyothi

You can use deep method for the array of objects.

您可以对对象数组使用 deep 方法。

expect([{a:1},{b:2}]).to.deep.include({b:2});   //It will pass

You can find more examples using deep method here: http://chaijs.com/api/bdd/#method_deep

你可以在这里找到更多使用深度方法的例子:http: //chaijs.com/api/bdd/#method_deep

The main point to remember here is about reference types.

这里要记住的要点是关于引用类型。