【发布时间】:2014-10-09 01:51:25
【问题描述】:
我正在使用带有内联要求的 requirejs,例如:
define(['someDep'], function(someDep) {
return {
someFn: function() {
require(['anotherDep'], function(anotherDep) {
anotherDep.anotherFn();
});
}
}
});
在我的特殊情况下,我不能在定义中包含 anotherDep。
在使用 mocha 进行测试时,我有一个这样的测试用例:
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 直接调用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();
});
});
有没有更好的方法?如果没有,希望这能为遇到同样问题的其他人提供解决方案。
【问题讨论】:
标签: javascript unit-testing requirejs mocha.js squirejs