该答案基于Andreas Köberle 的答案。
实施和理解他的解决方案对我来说并不容易,所以我将更详细地解释它是如何工作的,以及要避免的一些陷阱,希望它对未来的访问者有所帮助。
所以,首先是设置:
我使用Karma作为测试运行器,使用MochaJs作为测试框架。
使用Squire之类的东西对我不起作用,出于某种原因,当我使用它时,测试框架会抛出错误:
TypeError:无法读取未定义的属性“调用”
RequireJs可以将模块 ID映射到其他模块 ID。它还允许创建一个使用不同于全局配置的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);
}
});
});
});
});
});
});