Reputation: 838
I'm using the assert
syntax of chai for this.
I know that if I want to check an array of objects for a specific object, I can do this:
assert.deepInclude(
[
{ name: 'foo', id: 1 },
{ name: 'bar', id: 2 }
],
{ name: 'foo', id: 1 }
)
Which should pass.
But what if I only have 1 property in the object that I'm checking for...? Like this:
assert.deepInclude(
[
{ name: 'foo', id: 1 },
{ name: 'bar', id: 2 }
],
{ name: 'foo' }
)
I still want this to pass, but it's telling me it's failing because that exact object does not exist.
Upvotes: 5
Views: 3251
Reputation: 24555
Using chai-subset this can be done pretty easily:
const chai = require('chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);
it('should contain subset', () => {
const actual = [
{ name: 'foo', id: 1 },
{ name: 'bar', id: 2 },
];
expect(actual).to.containSubset([{ name: 'foo' }]);
});
Afaik there's no way to do this with chai
alone, but you could write your own function:
function containsPartialObj(arr, obj) {
return arr.some(entry => {
const keys = Object.keys(obj);
return keys.every(key => obj[key] === entry[key]);
});
}
it('should contain subset', () => {
const actual = [
{ name: 'foo', id: 1 },
{ name: 'bar', id: 2 },
];
expect(containsPartialObj(actual, { name: 'foo' })).to.be.true;
});
Upvotes: 7