Skip to content

Instantly share code, notes, and snippets.

@blackswanny
Last active September 30, 2015 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackswanny/3fa3ae09b35584963ad4 to your computer and use it in GitHub Desktop.
Save blackswanny/3fa3ae09b35584963ad4 to your computer and use it in GitHub Desktop.
beforeEach(function() {
jasmine.addMatchers(getCustomMatcher());
});
function getCustomMatcher() {
function createCustomMatcher(arg, util, customEqualityTesters) {
return sinon.match(function (val) {
return util.equals(val, arg, customEqualityTesters);
});
}
var messageFactories = {
spyWithOtherArgs: function(txt) {
return function(pass, spy, otherArgs) {
return messageUtils.expectedSpy(pass, spy, txt) + ' ' +
messageUtils.otherArgs(otherArgs);
};
}
};
var messageUtils = {
expectedSpy: function(pass, spy, txt) {
var not = (pass ? 'not ' : '');
var printf = spy.printf || sinon.spy.printf;
return printf.call(spy, 'Expected spy "%n" %1%2', not, txt);
},
otherArgs: function(otherArgs) {
if (!otherArgs || !otherArgs.length) {
return '';
} else if (otherArgs.length > 1) {
return jasmine.pp(otherArgs);
} else {
return jasmine.pp(otherArgs[0]);
}
}
};
var matchers = [
{
sinonName: 'calledOn',
jasmineName: 'toHaveBeenCalledOn',
message: messageFactories.spyWithOtherArgs('to have been called on')
},
{
sinonName: 'calledWith',
jasmineName: 'toHaveBeenCalledWith',
message: messageFactories.spyWithOtherArgs('to have been called with')
}
];
function assertSinon(actual, sinonMatcherName, args) {
var sinonProperty = actual[sinonMatcherName], pass;
if (typeof sinonProperty === 'function') {
pass = sinonProperty.apply(actual, args);
} else {
pass = sinonProperty;
}
return {
pass: pass,
message: matchers[0].message(pass, actual, args)
};
}
return {
toHaveBeenCalledWithJQuery: function(util, customEqualityTesters) {
return {
compare: function () {
var arg;
var args = [].slice.call(arguments, 0);
var actual = args[0];
for (var i = 0, len = args.length; i < len; i++) {
arg = args[i];
if (arg && (typeof arg.jasmineMatches === 'function' || arg instanceof jasmine.ObjectContaining)) {
args[i] = createCustomMatcher(arg, util, customEqualityTesters);
}
}
var calledOn = assertSinon(actual, matchers[0].sinonName, [sinon.match(function (element) {
return element.selector === args[1];
})]);
if (calledOn.pass) {
var scopeCall, calledWith;
for (var j = 0; j < actual.callCount; j++) {
scopeCall = actual.getCall(j);
if (scopeCall.thisValue.selector === args[1]) {
calledWith = assertSinon(scopeCall, matchers[1].sinonName, args.slice(2));
if (calledWith.pass) {
break;
}
}
}
return calledWith;
} else {
return calledOn;
}
}
};
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment