Ota*_*edo 5 jquery greasemonkey unit-testing google-chrome userscripts
我正在编写一个 Greasemonkey 用户脚本,该脚本应该使用 jQuery 并在 Google Chrome 和 Firefox 上运行。
我已经看到了几个如何做到这一点的例子,其中包括关于 SO 的非常好的答案。所有这些都归结为调用“注入脚本”函数,并将另一个回调函数作为参数传递。
该回调函数内的代码是“魔法”发生的地方,包括访问jQuery( $) 对象。
这个解决方案效果很好。但是,使用它的后果之一是回调函数外部定义的函数无法从回调函数内部调用:
function doSomethingImportantThatIWantToUnitTest(){ ... }
function with_jquery(callback) {
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + callback.toString() + ")(jQuery)";
document.body.appendChild(script);
};
with_jquery(function ($) {
doSomethingImportantThatIWantToUnitTest(); // <---- meh. Not defined!
});
Run Code Online (Sandbox Code Playgroud)
所以,我只能使用回调函数中定义的函数。但反过来,这些函数也不能从外部调用。特别是,例如,它们不能从单元测试中调用,这对我来说非常烦人。
有没有办法为 Chrome 编写 Greasemonkey 脚本并对其进行单元测试?
您应该能够将任何您想要的内容传递到回调函数中,包括函数变量。
var f = function doSomethingImportantThatIWantToUnitTest(){ ... }
function with_jquery(callback) {
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + callback.toString() + ")(jQuery,f)";
document.body.appendChild(script);
};
with_jquery(function ($, f) {
f(); // <---- DEFINED!
});
Run Code Online (Sandbox Code Playgroud)
如果您想要执行多个函数,并且不想在多个不同位置更新代码,则可以传入一个对象或数组,该对象或数组将所有函数作为对象属性或数组中的元素。
但如果是我,我只会在您使用它们的范围内定义函数。
| 归档时间: |
|
| 查看次数: |
2456 次 |
| 最近记录: |