chai-spies-augment
Version:
Additions to chai-spies, adding utilities to inspect args and check if a spy was called with a partial object
70 lines (54 loc) • 2.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/**
* Adds option to check if a spy was called with a partial object
* This will check if any paramater, in any of the spy's calls, is an object containing the passed in value
*
* @example
* const spy = chai.spy();
*
* spy({ a: 'b', c: 'd' });
* spy(1, 'a', { b: 'c' });
*
* expect(spy).to.have.been.called.with.objectContaining({ a: 'b' }); // true
* expect(spy).to.have.been.called.with.objectContaining({ b: 'c' }); // true
*
*/
exports.default = function () {
_chai.Assertion.addMethod('objectContaining', objectContaining);
function objectContaining(matchObject) {
new _chai.Assertion(this._obj).to.be.spy;
var spy = this._obj.__spy;
var calls = spy.calls;
var callsContainObject = calls.some(function (args) {
return args.some(function (arg) {
return argContainsObject(arg, matchObject);
});
});
this.assert(callsContainObject === true, 'expected spy to have been called with object containing #{exp}\n actual calls: #{act}', 'expected spy not to have been called with object containing #{exp}', matchObject, JSON.stringify(calls));
}
function argContainsObject(arg, matchObject) {
var matchTotal = Object.keys(matchObject).length;
var matches = 0;
if ((typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object') {
for (var key in matchObject) {
var value = matchObject[key];
if (Array.isArray(value) || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
if (_lodash2.default.isEqual(value, arg[key])) {
matches++;
}
} else if (arg[key] === value) {
matches++;
}
}
}
return matches === matchTotal;
}
};
var _chai = require('chai');
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }