Skip to content
Advertisement

Chai test array of objects to “contain something like” an object submatch

Ok. I’ve tried to read other questions here but still didn’t find a straightforward answer.

How can I assert a partial object match in an array using chai? Something like the following:

var expect = require('chai').expect;
var data = [ { name: 'test', value: 'bananas' } ];
expect(data).to.be.an('array').that.contains.somethig.like({name: 'test'});

Just to clarify, my intention is to get as close to the example provided as possible.

  • to chain after the .be.an('array') and
  • to provide only the partial object as a parameter (unlike chai-subset).

I really thought that expect(data).to.be.an('array').that.deep.contains({name: 'test'}); would work, but it fails on not being a partial match and I’m kinda screwed there.

Advertisement

Answer

Since chai-like@0.2.14 the following approch will work:

var chai = require('chai'),
    expect = chai.expect;

chai.use(require('chai-like'));
chai.use(require('chai-things')); // Don't swap these two

expect(data).to.be.an('array').that.contains.something.like({name: 'test'});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement