Match partial objects in Tea statements?

I am looking for a better way to match the following:

expect([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).to.deep.include.members([ { C1: 'xxx' } ]); 

The above does not work, because C0 exists in the actual, but not expected. In short, I want this to be expected to go through, but I'm not sure how to do this without writing a bunch of my own code ...

+13
chai
source share
7 answers

chai-subset or chai-fuzzy can also do what you are looking for.

Chai-subset should work like this:

 expect([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).to.containSubset([{C1: 'xxx'}]); 

Personally, if I do not want to include another plugin, I will use the property or matching keys , which includes Chai:

 ([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).forEach(obj => { expect(obj).to.have.key('C1'); // or... expect(obj).to.have.property('C1', 'xxx'); }); 
+8
source share

There are several different plugins that solve this problem. I am a fan of shallow, deep, equal . You would use it like this:

 expect([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).to.shallowDeepEqual([ { C1: 'xxx' } ]); 
+4
source share

without plugins: http://chaijs.com/api/bdd/#method_property

  expect([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).to.have.deep.property('[0].C1', 'xxx'); 
+2
source share

I believe that the simplest (and, of course, the simplest) way would be:

 var actual=[ { C1:'xxx', C0:'yyy' } ]; actual.forEach(function(obj){ expect(obj).to.have.property('C1','xxx'); }); 
0
source share

I wrote chai-match-pattern and lodash-match-pattern to handle incompatible scripts (and many others).

 var chai = require('chai'); var chaiMatchPattern = require('chai-match-pattern'); chai.use(chaiMatchPattern); // Using JDON pattern in expectation chai.expect([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).to.matchPattern([ { C1: 'xxx', '...': '' } ]); // Using the slightly cleaner string pattern notation in expectation chai.expect([ { C1: 'xxx', C0: 'this causes it not to match.' } ]).to.matchPattern(` [ { C1: 'xxx', ... } ] ` ); 
0
source share

A slightly updated version of #RobRaisch, because an error is generated for an empty comparison, because `` does not equal ''

 let expected = { dateOfBirth: '', admissionDate: '', dischargeDate: '', incidentLocation: null }; Object.keys(expected).forEach(function(key) { expect(actual[key]).to.equal(expected[key]); }); 
0
source share

You can use the pick and omit underscore functions to select / reject properties for validation:

 const { pick, omit } = require('underscore'); const obj = { C1: 'xxx', C0: 'this causes it not to match.', }; it('tests sparse object with pick', () => { expect(pick(obj, 'C1')).to.eql({ C1: 'xxx' }); }); it('tests sparse object with omit', () => { expect(omit(obj, 'C0')).to.eql({ C1: 'xxx' }); }); 
0
source share

All Articles