gpt4 book ai didi

javascript - 如何递归设置 RequireJS 上下文

转载 作者:行者123 更新时间:2023-12-03 11:53:06 25 4
gpt4 key购买 nike

我正在尝试将 Jasmine 测试添加到我的 Marionette 应用程序中,方法是为每个测试创建一个特定的上下文,其中包含一个映射,该映射用模拟替换除正在测试的模块之外的所有依赖项(如下所述: http://bocoup.com/weblog/effective-unit-testing-with-amd/ )。

mockRequire = requirejs.config({
map: {
'*': {
'dep1': '../mocks/dep1'
}
}
});
mockRequire(['appTest'], function(){...})

但是,由于我的模块 appTest 有一个嵌套调用,要求上下文丢失:

//appTest.js
define([],
function () {
...
require(['dep1'], function (dep1) {
//Here is not the mocked dep1 but the real one.
})
}
);

所以问题是我如何告诉 requirejs 对 require/define 的所有子调用使用相同的上下文,或者是否有其他方法来解决这个问题。

最佳答案

更改模块定义,使其需要 require:

define(['require'], function (require) {

没有它,您将使用全局 require。有了它,您可以使用具有正确上下文的require。来自 the documentation :

Note that "require" is specified as a dependency for the module. This allows the require() function that is passed to the function callback to use the right context to load the modules correctly for multiversion support. If "require" is not specified as a dependency, then there will likely be an error.

关于javascript - 如何递归设置 RequireJS 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com