Skip to content

Instantly share code, notes, and snippets.

@caseyhoward
Created January 27, 2016 06:19
Show Gist options
  • Save caseyhoward/6b36e327808d04fe6de7 to your computer and use it in GitHub Desktop.
Save caseyhoward/6b36e327808d04fe6de7 to your computer and use it in GitHub Desktop.
// This is a hack for stubbing functions with arguments in jasmine2
function With(stub, values) {
this.stub = stub;
this.values = values;
}
With.prototype.andReturn = function (returnValue) {
this.stub.addStubbedCall(this.values, returnValue);
};
function Stub() {
this.stubbedCalls = [];
}
Stub.prototype.with = function () {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i - 0] = arguments[_i];
}
return new With(this, values);
};
Stub.prototype.addStubbedCall = function (values, returnValue) {
this.stubbedCalls.push({ values: values, returnValue: returnValue });
};
Stub.prototype.andReturn = function (returnValue) {
this.addStubbedCall([], returnValue);
};
Stub.prototype.getStubbedReturnValue = function (values) {
var stubbedCall = _.find(this.stubbedCalls, function (value) { return _.isEqual(value.values, values); });
return stubbedCall && stubbedCall.returnValue;
};
function stub(object, functionName) {
var stub = new Stub();
if (!object[functionName].calls) {
spyOn(object, functionName).and.callFake(function fake() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i - 0] = arguments[_i];
}
return stub.getStubbedReturnValue(values);
});
}
return stub;
}
// example usage
let x = {add: function(x, y) {}};
stub(x, 'add').with(1, 2).andReturn(3);
stub(x, 'add').with(2, 3).andReturn(5);
console.log(x.add(1, 2)); // logs 3
console.log(x.add(2, 3)); // logs 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment