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.
.be.an('array')
andI 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.
Since [email protected]
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'});
Clean, functional and without dependencies, simply use a map to filter the key you want to check
something like:
const data = [ { name: 'test', value: 'bananas' } ];
expect(data.map(e=>e.name)).to.include("test");
and if you want to test multiple keys:
expect(data.map(e=>({name:e.name}))).to.include({name:"test"});
https://www.chaijs.com/api/bdd/
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