我在使用testr.js模拟RequireJS依赖项时遇到了一些小问题。我有以下目录结构:
<root>
|-- Scripts
| |-- lib
| | +-- require.js
| +-- modules
| |-- dependency.js
| +-- testable-thing.js
|-- Test
| |-- lib
| | +-- testr.js
| +-- index.html
+-- index.html在本例中,正在测试的系统将是testable-thing.js,我希望使用testr切换的依赖项是dependency.js。以下是源代码:
// testable-thing.js
define(["scripts/modules/dependency"], function (dep) {
console.log("testable thing loaded");
});
// dependency.js
define(function () {
console.log("dependency loaded");
});当使用http://<root>/index.html (下面的源代码)请求require-config.js时,工作正常,并记录到控制台:

我还有一个入口点http://<root>/test/index.html,它将在一个完整的应用程序中运行JavaScript单元测试。看起来是这样的:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="/scripts/lib/require.js"></script>
<script src="/test/lib/testr.js"></script>
</head>
<body>
<script>
testr.config({
root: "../"
});
testr.run("/scripts/require-config.js", function () {
console.log("entering tests");
var sut = testr("modules/testable-thing", {
"modules/dependency": function () {
console.log("stub loaded");
}
});
});
</script>
</body>
</html>这就是我遇到麻烦的地方。它给出了这样的输出:

现在,我了解到testr.js覆盖RequireJS的require方法来注册加载了哪些模块,并用传递给testr函数的存根/模拟覆盖它们,但在我的一生中,我无法解决如何“加载”这些依赖项。如果我在test/index.html中修改test/index.html回调例程,以包含一些确实会加载依赖项的内容:
testr.run("/scripts/require-config.js", function () {
console.log("entering tests");
require(["modules/testable-thing"], function () { });
var sut = testr("modules/testable-thing", {
"modules/dependency": function () {
console.log("stub loaded");
}
});
});然后发生了这样的事情:

我真的不知道为什么entering tests会在这里打印两次。它只出现在源代码中的一个地方。
这是我的<root>/index.html和<root>/scripts/require-config.js
// <root>/index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="/scripts/lib/require.js" data-main="/scripts/require-config.js"></script>
</head>
<body>
<script>
require(["modules/testable-thing"], function (testableThing) {
});
</script>
</body>
</html>// <root>/scripts/require-config.js
require.config({
baseUrl: "/scripts"
});如何通过模拟这些依赖项来启动和运行?在请求<root>/test/index.html时,我希望看到:
entering tests
stub loaded
testable thing loaded在Chrome控制台。
发布于 2013-09-22 21:47:43
我有一件事有点不对劲。在http://<root>/tests/index.html中
require(["modules/testable-thing"], function () {
console.log("entering tests");
var sut = testr("modules/testable-thing", {
"modules/dependency": {
run: function () {
console.log("stub loaded");
}
}
});
});注意测试是如何在回调传递给require()时运行的。Boilerplatejs撰稿人Janith的这篇文章在这方面很有帮助。
此外,在当前版本的testr中似乎存在一个bug。使用最新的(1.3.2),我们得到了以下输出:

然而,使用1.0.2 ( Boilerplatejs所使用的),我们获得了成功:

今晚再做些调查看看这是怎么回事。
https://stackoverflow.com/questions/18907259
复制相似问题