I'm trying to validate that an array of objects like this:
[
{
a: 1,
b: 2,
c: 3
},
{
a: 4,
b: 5,
c: 6
},
...
]
contains at least one object with both { a: 1 }
and { c: 3 }
:
I thought I could do this with chai-things, but I don't know all the properties of the object to be able to use
expect(array).to.include.something.that.deep.equals({ ??, a: 1, c: 3});
and contain.a.thing.with.property
doesn't work with multiple properties :/
What's the best way to test something like this?
Most elegant solution I could come up with (with the help of lodash):
expect(_.some(array, { 'a': 1, 'c': 3 })).to.be.true;
The desired solution seems to be something like:
expect(array).to.include.something.that.includes({a: 1, c: 3});
I.e. array
contains an item which includes those properties. Unfortunately, it appears to not be supported by chai-things at the moment. For the foreseeable future.
After a number of different attempts, I've found that converting the original array makes the task easier. This should work without additional libraries:
// 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});
This also allows you to check for several objects at the same time (my use case).
expect(simplifiedArray).to.include.deep.members([{
a: 1,
c: 3
}, {
a: 3,
c: 5
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With