该答案基于AndreasKöberle的答案。
对我来说,实施和理解他的解决方案并不容易,所以我将更详细地解释它的工作原理,并避免一些陷阱,希望它能对将来的访问者有所帮助。
因此,首先进行设置:
我使用Karma作为测试运行程序,并使用MochaJs作为测试框架。
使用Squire之类的东西对我不起作用,由于某种原因,当我使用它时,测试框架引发错误:
TypeError:无法读取未定义的属性“ call”
RequireJs可以将模块ID 映射到其他模块ID。它还允许创建使用与global 不同的配置的require
函数。
这些功能对于该解决方案的工作至关重要。require
这是我的模拟代码版本,包括(很多)注释(我希望它是可以理解的)。我将其包装在模块中,以便测试可以轻松地需要它。
define([], function () {
var count = 0;
var requireJsMock= Object.create(null);
requireJsMock.createMockRequire = function (mocks) {
//mocks is an object with the module ids/paths as keys, and the module as value
count++;
var map = {};
//register the mocks with unique names, and create a mapping from the mocked module id to the mock module id
//this will cause RequireJs to load the mock module instead of the real one
for (property in mocks) {
if (mocks.hasOwnProperty(property)) {
var moduleId = property; //the object property is the module id
var module = mocks[property]; //the value is the mock
var stubId = 'stub' + moduleId + count; //create a unique name to register the module
map[moduleId] = stubId; //add to the mapping
//register the mock with the unique id, so that RequireJs can actually call it
define(stubId, function () {
return module;
});
}
}
var defaultContext = requirejs.s.contexts._.config;
var requireMockContext = { baseUrl: defaultContext.baseUrl }; //use the baseUrl of the global RequireJs config, so that it doesn't have to be repeated here
requireMockContext.context = "context_" + count; //use a unique context name, so that the configs dont overlap
//use the mapping for all modules
requireMockContext.map = {
"*": map
};
return require.config(requireMockContext); //create a require function that uses the new config
};
return requireJsMock;
});
我遇到的最大陷阱是创建RequireJs配置,这实际上使我花费了几个小时。我试图(深层)复制它,并且仅覆盖必要的属性(例如上下文或地图)。这行不通!仅复制baseUrl
,这可以正常工作。
用法
要使用它,请在测试中要求它,创建模拟,然后将其传递给createMockRequire
。例如:
var ModuleMock = function () {
this.method = function () {
methodCalled += 1;
};
};
var mocks = {
"ModuleIdOrPath": ModuleMock
}
var requireMocks = mocker.createMockRequire(mocks);
这里是完整测试文件的示例:
define(["chai", "requireJsMock"], function (chai, requireJsMock) {
var expect = chai.expect;
describe("Module", function () {
describe("Method", function () {
it("should work", function () {
return new Promise(function (resolve, reject) {
var handler = { handle: function () { } };
var called = 0;
var moduleBMock = function () {
this.method = function () {
methodCalled += 1;
};
};
var mocks = {
"ModuleBIdOrPath": moduleBMock
}
var requireMocks = requireJsMock.createMockRequire(mocks);
requireMocks(["js/ModuleA"], function (moduleA) {
try {
moduleA.method(); //moduleA should call method of moduleBMock
expect(called).to.equal(1);
resolve();
} catch (e) {
reject(e);
}
});
});
});
});
});
});
define
功能。虽然有一些不同的选择。我将发布答案,希望对您有所帮助。