[英]Chai expect: an array to contain an object with at least these properties and values
我正在尝试验证这样的对象数组:
[
{
a: 1,
b: 2,
c: 3
},
{
a: 4,
b: 5,
c: 6
},
...
]
包含至少一个同时具有{ a: 1 }
和{ c: 3 }
:
我以为我可以用chai-things做到这一点,但我不知道对象的所有属性都可以使用
expect(array).to.include.something.that.deep.equals({ ??, a: 1, c: 3});
并且contain.a.thing.with.property
不适用于多个属性:/
测试这样的东西的最佳方法是什么?
我能想到的最优雅的解决方案(在 lodash 的帮助下):
expect(_.some(array, { 'a': 1, 'c': 3 })).to.be.true;
所需的解决方案似乎是这样的:
expect(array).to.include.something.that.includes({a: 1, c: 3});
即array
包含一个包含这些属性的项目。 不幸的是,它目前似乎不受 chai-things 的支持。 在可预见的未来。
经过多次不同的尝试,我发现转换原始数组使任务更容易。 这应该可以在没有额外库的情况下工作:
// Get items that interest us/remove items that don't.
const simplifiedArray = array.map(x => ({a: x.a, c: x.c}));
// Now we can do a simple comparison.
expect(simplifiedArray).to.deep.include({a: 1, c: 3});
这也允许您同时检查多个对象(我的用例)。
expect(simplifiedArray).to.include.deep.members([{
a: 1,
c: 3
}, {
a: 3,
c: 5
}]);
似乎来自chai
的chai-subset
插件似乎成功了。 这是我正在做的事情:
const chai = require('chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);
const expect = chai.expect;
expect([ { type: 'text',
id: 'name',
name: 'name',
placeholder: 'John Smith',
required: 'required' },
{ type: 'email',
id: 'email',
name: 'email',
placeholder: 'example@gmail.com',
required: 'required' },
{ type: 'submit' } ]).containSubset([{ type: 'text', type: 'email', type: 'submit' }]);
我能想到的最直接的方法是:
const chai = require('chai');
const expect = chai.expect;
chai.use(require('chai-like'));
chai.use(require('chai-things'));
expect([
{
a: 1,
b: 2,
c: 3,
},
{
a: 4,
b: 5,
c: 6,
},
]).to.be.an('array').that.contains.something.like({ a: 1, c: 3 });
您可以编写自己的函数来测试数组。 在此示例中,您传入数组和包含相关键/值对的对象:
function deepContains(arr, search) {
// first grab the keys from the search object
// we'll use the length later to check to see if we can
// break out of the loop
var searchKeys = Object.keys(search);
// loop over the array, setting our check variable to 0
for (var check = 0, i = 0; i < arr.length; i++) {
var el = arr[i], keys = Object.keys(el);
// loop over each array object's keys
for (var ii = 0; ii < keys.length; ii++) {
var key = keys[ii];
// if there is a corresponding key/value pair in the
// search object increment the check variable
if (search[key] && search[key] === el[key]) check++;
}
// if we have found an object that contains a match
// for the search object return from the function, otherwise
// iterate again
if (check === searchKeys.length) return true;
}
return false;
}
deepContains(data, { a: 4, c: 6 }); // true
deepContains(data, { a: 1, c: 6 }); // false
没有第三方库或插件的解决方案:
let array = [
{ a: 1, b: 2, c: 3 },
{ a: 4, b: 5, c: 6 }
];
let match = array.map(({a, c}) => ({a, c})).to.deep.include({ a:1, c:3});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.