I am looking for the best way to match the following:
expect([
{
C1: \'xxx\',
C0: \'this causes it not to match.\'
}
]).to.deep.incl
I believe the simplest (and certainly easiest) way would be to:
var actual=[
{
C1:'xxx',
C0:'yyy'
}
];
actual.forEach(function(obj){
expect(obj).to.have.property('C1','xxx');
});
I wrote chai-match-pattern and lodash-match-pattern to handle partial matching (and many more) deep matching scenarios.
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',
...
}
]
`
);
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');
There are a few different chai plugins which all solve this problem. I am a fan of shallow-deep-equal. You'd use it like this:
expect([
{
C1: 'xxx',
C0: 'this causes it not to match.'
}
]).to.shallowDeepEqual([
{
C1: 'xxx'
}
]);
You can use pick
and omit
underscore functions to select/reject properties to test:
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' });
});
Slightly updated version of #RobRaisch because for empty comparison giving error because '' not equal ""
let expected = {
dateOfBirth: '',
admissionDate: '',
dischargeDate: '',
incidentLocation: null
};
Object.keys(expected).forEach(function(key) {
expect(actual[key]).to.equal(expected[key]);
});