我将 requirejs 与内联需求一起使用,例如:
define(['someDep'], function(someDep) {
return {
someFn: function() {
require(['anotherDep'], function(anotherDep) {
anotherDep.anotherFn();
});
}
}
});
就我的具体情况而言,我不能包括anotherDep
在定义中。
使用摩卡进行测试时,我有一个这样的测试用例:
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();
});
});
});
});
失败是因为anotherDep
calls require
直接和不squire.require
。解决方法是更换require
在全球范围内,
var originalRequire;
before(function() {
originalRequire = require;
require = _.bind(squire.require, squire);
});
after(function() {
require = originalRequire;
});
这有效(请注意squire.require
必须绑定到squire
对象以某种方式,我使用下划线来执行此操作),但由于时间原因,间谍仍然不会被调用。测试也必须更改为
it('should mock anotherDep', function(done) {
squire.mock('anotherDep', {
anotherFn: function() {
done();
}
});
squire.require(['someDep'], function(someDep) {
someDep.someFn();
});
});
有没有更好的办法?如果没有,希望这能为遇到同样问题的其他人提供解决方案。