Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 994
kub1x Avatar asked Dec 14 '22 22:12

kub1x


2 Answers

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'});
like image 97
kub1x Avatar answered Dec 21 '22 11:12

kub1x


ES6+

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/

like image 39
Sebastien Horin Avatar answered Dec 21 '22 10:12

Sebastien Horin