Skip to content

Instantly share code, notes, and snippets.

@vojtech-dobes
Created October 19, 2012 10:31
Show Gist options
  • Save vojtech-dobes/3917417 to your computer and use it in GitHub Desktop.
Save vojtech-dobes/3917417 to your computer and use it in GitHub Desktop.
Require.js + Mocha + Sinon
var requirejs = require('requirejs');
var _ = require('underscore');
var sinon = require('sinon');
requirejs.define(function (undefined) {
var createContext = function (name, stubs) {
var map = {};
var prefix = 'stub' + name + ':';
_.each(stubs || {}, function (value, key) {
map[key] = prefix + key;
requirejs.define(prefix + key, function () {
if (typeof value == 'object') {
_.each(value, function (method, key) {
if (typeof method == 'object' && method.stub) {
var stub = sinon.stub();
if (typeof method.stub == 'function') {
method.stub(stub);
}
value[key] = stub;
}
});
}
return value;
});
});
return requirejs.config({
baseUrl: __dirname + '/../js',
nodeRequire: require,
context: prefix,
map: {
"*": map
}
});
};
return function (name, stubs, suite) {
var i = 1;
if (!suite && typeof stubs == 'function') {
suite = stubs;
}
var testCase = function (msg, test, depstubs) {
var load = createContext(name + i, stubs);
i++;
if (test) {
var xtest = it(msg, function (done) {
var deps = [name];
testCase.done = done;
_.each(depstubs || [], function (stub) {
deps.push(stub);
});
requirejs.define(name + i + 'done', function () {
return done;
});
deps.push(name + i + 'done');
load(deps, test);
});
} else {
it(msg);
}
};
if (suite) {
suite(testCase);
}
return testCase;
};
});
var load = requirejs('bootstrap')('nameOfTestedThing', {
	nameOfDependency: mockOfDependency
}, function (test) {

describe('foo', function () {
	test('bar', function (testedThing, mockOfDependency) {
		...
		test.done();
	}, ['nameOfDependency']);
});

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