Alec Mather
Alec Mather

Reputation: 838

Mocha Chai: Deep include an array of objects, but only have part of expected object

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

Answers (1)

eol
eol

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

Related Questions