Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Created February 22, 2011 00:22
Show Gist options
  • Save atesgoral/837988 to your computer and use it in GitHub Desktop.
Save atesgoral/837988 to your computer and use it in GitHub Desktop.
Very simple mock library
/**
* Note: Has hard-coded dependency on a CommonJS Unit Test 1.0 assertion module,
* but doesn't have to.
*/
function Mock(intf) {
var expectations, failures, expect = {};
for (var p in intf) {
if (intf.hasOwnProperty(p) && typeof intf[p] === "function") {
(function ($p) {
this[$p] = function () {
var args = [].slice.call(arguments),
expectation = expectations.shift();
try {
assert.ok(expectation,
"Unexpected function call");
assert.equal(expectation.name, $p,
"Unmatched function call");
for (var i = 0; i < args.length; ++i) {
assert.deepEqual(expectation.args[i], args[i],
"Unmatched argument at index " + i);
}
return expectation.action && expectation.action();
} catch (e) {
failures.push(e.message ? e.message : e);
}
};
expect[$p] = function () {
var expectation = {
name: $p,
args: [].slice.call(arguments)
};
expectations.push(expectation);
return {
thenReturn: function (ret) {
expectation.action = function () {
return ret;
};
},
thenDo: function (fn) {
expectation.action = fn;
return this;
}
};
};
}).call(this, p);
}
}
this.reset = function () {
expectations = [];
failures = [];
return this;
};
this.expect = function () {
return expect;
};
this.verify = function () {
if (failures.length) {
assert.ok(false, failures.join());
}
return this;
};
this.reset();
}
@atesgoral
Copy link
Author

Usage:

var mock = new Mock({
    doThis: function () {},
    doThat: function () {}
});

mock.expect().doThis(42);
mock.expect().doThat("abc", "def").thenReturn("abcdef");

// Do something that uses the Mock instance

mock.verify();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment