问题
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.
回答1:
I've not tried to do specifically what you are trying to do but it seems to me that if squire is doing a thorough job, then requiring the require module should give you what you want without having to mess with the global require. The require module is a special (and reserved) module that makes available a local require function. It is necessary for instance when you use the Common JS syntactic sugar. However, you can use it whenever you desire to get a local require. Again, if squire does a thorough job, then the require it gives you should be one that squire controls rather than some sort of pristine require.
So:
define(['require', 'someDep'], function (require, someDep) {
return {
someFn: function() {
require(['anotherDep'], function(anotherDep) {
anotherDep.anotherFn();
});
}
}
});
来源:https://stackoverflow.com/questions/26269119/how-to-mock-inline-requirejs-dependencies-with-squire-for-unit-testing