如何在dalekjs.execute()中执行外部函数



我想在dalekjs的.execute()函数内执行一个外部函数。有可能做到吗?

取决于external的含义。

如果要执行客户端JavaScript中已经存在的函数,则必须可以通过全局window对象访问该函数。例如:

在我的一个客户端脚本中,我有这样的东西:

function myAwesomeFn (message) {
$('body').append('<p>' + message + '</p>');
}

如果该函数是在全局范围内定义的(而不是在某些IIFE f.e.内),您可以在执行函数中触发它,如下所示:

test.execute(function () {
window.myAwesomeFn('Some message');
});

如果你的意思是"在Dalek测试套件中定义的函数"带有外部,我可能会让你失望,因为Daleks测试文件和execute函数的内容是在不同的上下文中调用的(甚至是不同的JavaScript引擎)。

所以这不起作用:

'My test': function (test) {
var myFn = function () { // does something };
test.execute(function () {
myFn(); // Does not work, 'myFn' is defined in the Node env, this functions runs in the browser env
})
}

什么有效:

'My test': function (test) {

test.execute(function () {
var myFn = function () { // does something };
myFn(); // Does work, myFn is defined in the correct scope
})
}

希望这能回答你的问题,如果不能,请提供更多细节。

编辑:

使用节点自身要求的加载文件

var helper = require('./helper');
module.exports = {
'My test': function (test) { 
test.execute(helper.magicFn)
}
};

在helper.js中,你可以随心所欲,这(或多或少)是有道理的:

module.exports = {
magicFn: function () { 
alert('I am a magic function, defined in node, executed in the browser!');
}
};

关于如何保持测试代码DRY的进一步策略;),检查此repo/文件:Dalek DRY示例

最新更新