将函数传递给nighmarejs evaluate()

时间:2017-06-21 10:19:03

标签: javascript node.js nightmare

我试图传递一个在nightmarejs evaluate语句中调用的函数并返回一个值。像这样:

var thisfunction = function() {
    var tags = [];
    var list = document.querySelector('#selectSomething');
    list.forEach(function(item) {
        tags.push({
            name: item.attributes[1].value,
            id: item.attributes[2].value
        })
    });
    return tags;
};

return nightmare
    .goto('url')
    .wait('#something')
    .evaluate(function(getValues) {
        getValues();
    }, thisfunction)
    .then(function(list) {
        console.log(list);
    })

我得到了ReferenceError: getValues is not defined。尝试了不同的方法,在不同的地方使用return语句,但没有运气。

如何做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:2)

我想您可以简单地编写以下代码:

var thisfunction = function() {
    var tags = [];
    var list = document.querySelector('#selectSomething');
    list.forEach(function(item) {
        tags.push({
            name: item.attributes[1].value,
            id: item.attributes[2].value
        })
    });
    return tags;
};

return nightmare
    .goto('url')
    .wait('#something')
    .evaluate(thisfunction)
    .then(function(list) {
        console.log(list);
    })

答案 1 :(得分:2)

行为背后的原因

在传递给evaluate方法之前,您可以将字符串/数字作为参数传递,但不能传递函数/对象,因为它们已经过序列化。

您可以查看解释here

此外,还有ticket on Github具有相似经历的用户。