Last active
December 17, 2015 03:39
-
-
Save dotfold/5544933 to your computer and use it in GitHub Desktop.
jasmine object introspection matcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
beforeEach(function() { | |
this.addMatchers({ | |
// | |
// ### function hasProperties expected | |
// #### @expected Array of Object or single Object with expected key value pairs. | |
// Custom matcher to verify that the actual object under test contains given | |
// properties with corresponding values. | |
// | |
// The matcher will fail if either the property does not exist, or the values do not match. | |
// | |
// Expected objects must contain `name` and `equals`; | |
// | |
// Usage: | |
// expect(myObject).hasProperties([ | |
// {name: 'id', equals: 'movideo'} | |
// ]); | |
// | |
hasProperties: function(expected) { | |
this.message = function () { | |
return msg; | |
} | |
var actual = this.actual; | |
var inst = typeof actual; | |
var msg = 'Expected ' + inst + ' to have '; | |
var notText = this.isNot ? " not" : ""; | |
// convert to array if not already | |
if (Object.prototype.toString.call(expected) !== '[object Array]') { | |
expected = [expected]; | |
} | |
var failure = expected.some(function(matcher) { | |
var propName = matcher.name; | |
var propVal = matcher.equals; | |
if (!actual.hasOwnProperty(propName)) { | |
msg += 'property ' + "'" + propName + "'" + ' but was not found.'; | |
// this means shortcut | |
return true; | |
} | |
var actualVal = actual[propName]; | |
if (actualVal !== propVal) { | |
msg += 'property ' + "'" + propName + "'" + ' with value ' + "'" + propVal + "'"; | |
msg += ' but was ' + "'" + actualVal + "'"; | |
// this means shortcut | |
return true; | |
} | |
}) | |
// return inverse of the some() operation, since it shortcuts on a failure | |
return !failure; | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment