Exclude keys to compare from a deep equal operation with chaijs expect.
Sometimes you'll need to exclude object properties that generate unique values while doing a deep equal operation. This plugin makes it easier to remove those properties before comparison.
https://github.com/chaijs/chai/issues/885
npm install chai-exclude --only=dev
yarn add chai-exclude --dev
const chai = require('chai');
const chaiExclude = require('chai-exclude');
chai.use(chaiExclude);
import { use } from 'chai';
import chaiExclude from 'chai-exclude';
use(chaiExclude);
import { use } from 'chai';
import chaiExclude = require('chai-exclude');
use(chaiExclude);
// The typings for chai-exclude are included with the package itself.
- Excluding a top level property from an object
expect({ a: 'a', b: 'b' }).excluding('a').to.deep.equal({ b: 'b' })
expect({ a: 'a', b: 'b' }).excluding('a').to.deep.equal({ a: 'z', b: 'b' })
- Excluding multiple top level properties from an object
const obj = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: 'e'
}
}
expect(obj).excluding(['a', 'c']).to.deep.equal({ b: 'b' })
expect(obj).excluding(['a', 'c']).to.deep.equal({ a:'z', b: 'b' })
- Excluding every property in a deeply nested object
const actual = {
a: 'a',
b: 'b',
c: {
a: 'a',
b: {
a: 'a',
d: {
a: 'a',
b: 'b',
d: null
}
}
},
d: ['a', 'c']
}
const expected = {
a: 'z', // a is excluded from comparison
b: 'b',
c: {
b: {
d: {
b: 'b',
d: null
}
}
},
d: ['a', 'c']
}
expect(actual).excludingEvery('a').to.deep.equal(expected)
- Excluding multiple properties in a deeply nested object
const actual = {
a: 'a',
b: 'b',
c: {
a: 'a',
b: {
a: 'a',
d: {
a: 'a',
b: 'b',
d: null
}
}
},
d: ['a', 'c']
}
const expected = {
b: 'b',
c: {
b: {
d: { // d is not removed because it is an object
b: 'b'
}
}
}
}
expect(actual).excludingEvery(['a', 'd']).to.deep.equal(expected)
Note: excludingEvery
will not remove the property if it is an object in a deeply nested object.
Contributions are welcome. If you have any questions create an issue here.