I'm using requirejs with inline requires, for instance:
define(['someDep'], function(someDep) {
return {
someFn: function() {
require(['anotherDep'], function(anotherDep) {
anotherDep.anotherFn();
});
}
}
});
In my particular case, I cannot include anotherDep in the define.
When testing with mocha, I have a test case like this:
define(['squire'], function(Squire) {
var squire = new Squire();
describe('testcase', function() {
it('should mock anotherDep', function(done) {
var spy = sinon.spy();
squire.mock('anotherDep', {
anotherFn: spy
});
squire.require(['someDep'], function(someDep) {
someDep.someFn();
expect(spy).to.have.been.calledOnce;
done();
});
});
});
});
fails because anotherDep calls require directly and not squire.require. The work-around is to replace require in the global scope,
var originalRequire;
before(function() {
originalRequire = require;
require = _.bind(squire.require, squire);
});
after(function() {
require = originalRequire;
});
This works (note that squire.require must be bound to the squire object in some way, I'm using underscore to do this) except that the spy will still not be called because of timing. The test also has to change to
it('should mock anotherDep', function(done) {
squire.mock('anotherDep', {
anotherFn: function() {
done();
}
});
squire.require(['someDep'], function(someDep) {
someDep.someFn();
});
});
Is there a better way? If not, hope this provides a solution for others running into the same problem.