gpt4 book ai didi

coffeescript - QUnit + CoffeeScript 范围

转载 作者:行者123 更新时间:2023-12-03 09:24:00 24 4
gpt4 key购买 nike

在 Javascript 中,污染全局命名空间通常被认为是一件坏事。这就是 Coffeescript 将你所有的 Javascript 封装在 (function() {}).call(this); 中的原因。包装。

但是,我已经开始为我的 Coffeescript 代码编写 QUnit 测试,而 QUnit 提示它找不到我的函数。

1. Died on test #1: getGoodNamePart is not defined
getGoodNamePart is not defined at Object.<anonymous> (file:///Users/kevin/Documents/docs/code/chrome/tests.js:2:10) at Object.run

我想在不污染全局命名空间的情况下测试变量。有什么好方法可以做到这一点?

这是我要测试的生成的 Javascript:
(function() {
getGoodNamePart = function(str) {
if (str.charAt(0) === '"') {
str.replace(/" <[^>]+>$"/g, "");
str.replace(/"/g, "");
return str;
} else if (str.charAt(0) === '<') {
str.replace(/<|>/g, "");
return str;
} else {
return str;
}
};
}).call(this);

我的 test.js 文件是:
test('getGoodNamePart()', function() {
equals(getGoodNamePart("\"Kev Burke\" <kev@inburke.com>"), "Kev Burke", "\"name\" <email> works");
equals(getGoodNamePart("", "", "empty string works"));
equals(getGoodNamePart("kev@inburke.com", "kev@inburke.com", "raw email works"));
return equals(getGoodNamePart("<kev@inburke.com>", "kev@inburke.com", "email inside carets -> carets get stripped"));
});

谢谢,
凯文

最佳答案

所以,你说你想测试getGoodNamePart不污染全局命名空间。但是,CoffeeScript 自动模块化每个文件(有充分的理由——参见 my answer here),这意味着跨文件访问函数的唯一方法是将它们附加到某个全局对象。 (我假设我们在这里讨论的是浏览器,而不是 CommonJS 环境,例如 Node.js,您将在其中使用 exports。)

这为您提供了三个选项:

  • 附上getGoodNamePartwindow .这是最简单的,因为唯一需要的更改是前缀 getGoodNamePartwindow. (或只是 @ ),但这当然会最大化命名空间污染。
  • 附上getGoodNamePart到已经附加到 window 的其他东西或 global .
  • 将您的测试移动到与 getGoodNamePart 相同的文件中(在 JS 世界中是一种不寻常的做法,但值得考虑,因为它保持全局命名空间不变,让您可以轻松地在代码和测试之间切换)。

  • 假设您想使用 #2,导出函数如 getGoodNamePart纯粹为了测试。称它们为“测试目标”。在每个带有测试目标的文件的顶部,添加
    window.testTargets ?= {}

    当你定义 getGoodNamePart , 写
    testTargets.getGoodNamePart = getGoodNamePart = (str) ->
    ...

    然后在 QUnit 测试套件的顶部,编写
    {getGoodNamePart} = testTargets

    获取功能。

    关于coffeescript - QUnit + CoffeeScript 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474703/

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