我试图在 casper.evaluate() 中设置一个值,稍后我将检查该值以运行测试,但它似乎不起作用。
isArticleOrReview = false;
casper.waitFor(function check() { //here I'm just waiting for jQuery to load
return this.evaluate(function() {
return jQuery.fn.jquery == '1.2.6';
});
}, function then() { //once jQuery has been loaded, do this stuff
this.evaluate(function() {
isArticleOrReview = (jQuery('body').hasClass('node-type-review') || jQuery('body').hasClass('node-type-article'));
__utils__.echo('isArticleOrReview ' + isArticleOrReview);
});
});
casper.then(function(){
casper.test.info('isArticleOrReview ' + isArticleOrReview);
});
对于输出,我得到:
isArticleOrReview true
isArticleOrReview false
我想读一下:
isArticleOrReview true
isArticleOrReview true
最佳答案
evaluate
已沙盒化。被求值的函数无法访问周围的代码,周围的代码也无法访问被求值的函数。这是来自 PhantomJS 的一个更简单的示例(Casper 的 evaluate
使用下面的示例):
var page = require('webpage').create();
page.open('http://google.com/', function(status) {
var titleVar = "NOT SET";
var titleReturn = page.evaluate(function() {
// This would result in an error:
// console.log('Variable in evaluate:', titleVar);
// ReferenceError: Can't find variable: titleVar
titleVar = document.title;
return document.title;
});
console.log('Return value from evaluate:', titleReturn);
console.log('Variable post evaluate:', titleVar);
phantom.exit();
});
正如您所发现的,这将打印
Return value from evaluate: Google
Variable post evaluate: NOT SET
如果您取消注释 evaluate
中的 console.log
行,您将看到 evaluate
崩溃并烧毁,因为该变量不存在.
因此,您只能通过 evaluate
参数传递值并返回值(并且只能是可 JSON 序列化的值):
isArticleOrReview = this.evaluate(function() {
return (jQuery('body').hasClass('node-type-review') || jQuery('body').hasClass('node-type-article'));
});
关于javascript - 如何从 casper.evaluate() 设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091901/