Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai expect: an array to contain an object with at least these properties and values

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?

like image 503
blub Avatar asked Dec 21 '15 15:12

blub


2 Answers

Most elegant solution I could come up with (with the help of lodash):

expect(_.some(array, { 'a': 1, 'c': 3 })).to.be.true;
like image 181
blub Avatar answered Sep 29 '22 17:09

blub


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
}]);
like image 29
Druckles Avatar answered Sep 29 '22 17:09

Druckles