Skip to content

Instantly share code, notes, and snippets.

@johnmcase
Last active August 29, 2015 14:18
Show Gist options
  • Save johnmcase/ee1e24bf66942fa230db to your computer and use it in GitHub Desktop.
Save johnmcase/ee1e24bf66942fa230db to your computer and use it in GitHub Desktop.
Jasmine toHavePropertyValues custom matcher
'use strict';
define([], function() {
var toHavePropertyValues = function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
// actual is an object
// expected is an object
// The actual must contain all properties specified in expected and have matching values
var result = {pass: true};
if(!expected) {
result.pass = false;
result.message = 'No expected values passed to "toHavePropertyValues"';
}
else {
for(var propName in expected) {
if(actual.hasOwnProperty(propName)) {
if(!util.equals(actual[propName], expected[propName], customEqualityTesters)) {
result.pass = false;
result.message = 'Expected ' + JSON.stringify(actual) + ' to have property [' + propName + '] with value: ' + expected[propName];
break;
}
}
else {
result.pass = false;
result.message = 'Expected ' + JSON.stringify(actual) + ' to have property named: ' + propName;
break;
}
}
}
return result;
}
};
};
var toContainPropertyValues = function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
// Actual is array
// Expected is an object with 1 or more properties
// The array must contain at least 1 element containing all specified properties
if (Object.prototype.toString.apply(actual) !== '[object Array]') {
return {pass: false, message: 'toContainPropertyValues matcher only matches against arrays'};
}
for(var i in actual) {
var result = toHavePropertyValues(util, customEqualityTesters).compare(actual[i], expected);
if(result.pass) {
return result;
}
}
return {
pass: false,
message: 'expected ' + JSON.stringify(actual) + ' to contain an element that matches properties: ' + JSON.stringify(expected)
};
}
};
};
var toEqualWithPropertyValues = function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
// Actual is array
// Expected is an array (must be of same length)
// Traverse all arrays. Apply toHavePropertyValues to each corresponding pair
if ((Object.prototype.toString.apply(actual) !== '[object Array]') ||
(Object.prototype.toString.apply(expected) !== '[object Array]') ||
actual.length !== expected.length) {
return {pass: false, message: 'toEqualWithPropertyValues matcher only works with arrays of equal length'};
}
for(var i in actual) {
var result = toHavePropertyValues(util, customEqualityTesters).compare(actual[i], expected[i]);
if(!result.pass) {
return result;
}
}
return {pass: true};
}
};
};
return {
toHavePropertyValues: toHavePropertyValues,
toContainPropertyValues: toContainPropertyValues,
toEqualWithPropertyValues: toEqualWithPropertyValues
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment