Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KamilSzot/2f5e99b0815c166d98ff to your computer and use it in GitHub Desktop.
Save KamilSzot/2f5e99b0815c166d98ff to your computer and use it in GitHub Desktop.
chai.use(function(chai, utils) {
function containsProperties(expected) {
var actual = this._obj;
var success = true;
if(!utils.flag(this, 'deep')) {
if(Array.isArray(expected)) {
this.assert(success = expected.subtract(Object.extended(actual).select(expected).keys()).length === 0, "expected "+JSON.stringify(actual)+" to have "+JSON.stringify(expected));
} else {
this.assert(success = Object.extended(actual).select(Object.keys(expected)).equals(expected), "expected "+JSON.stringify(actual)+" to have "+JSON.stringify(expected));
}
} else {
(function havePropertiesTree(actual, expected) {
if(!success) return;
if(typeof actual !== "object") {
if(actual != expected) {
success = false;
}
} else {
if(Object.keys(expected).subtract(Object.keys(actual)).length === 0) {
Object.keys(expected).forEach(function(v, k) {
havePropertiesTree(actual[k], expected[k]);
});
} else {
success = false;
}
}
})(actual, expected);
this.assert(success, "expected "+actual+" to contain "+expected+" as subtree");
}
return success;
}
chai.Assertion.addMethod('properties', containsProperties);
chai.Assertion.addMethod('calledWithObjectWithProperties', function(expected) {
var spy = this._obj;
this.assert(spy.callCount, "expected to be called but it wasn't");
var i;
for(i = 0; i < spy.callCount; i++) {
var args = spy.args[i];
var actual = args[0];
console.info(containsProperties.call({ _obj: actual, assert: function() {} }, expected));
if(containsProperties.call({ _obj: actual, assert: function() {} }, expected)) {
break;
}
}
this.assert(i < spy.callCount, "expected to be called with "+JSON.stringify(expected)+" but got "+JSON.stringify(spy.args));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment