我有一个小型测试应用程序,它使用 NightmareJS 作为 PhantomJS 的包装器我想测试元素上是否存在类。我有这段代码:
new Nightmare()
.goto(baseURL)
.evaluate(function() {
return document.querySelector('body');
}, function(element) {
element.className.should.equal(expected)
callback();
})
.run();
如何将参数传递给 querySelector 方法而不是对标记进行硬编码?
我试过了
var tag = body;
new Nightmare()
.goto(baseURL)
.evaluate(function() {
return document.querySelector(tag);
}, function(element) {
element.className.should.equal(expected)
callback();
})
.run();
但是 PhantomJS 总是返回找不到变量的错误。
如何完成将变量参数传递给 querySelector 方法?
最佳答案
PhantomJS 有两个上下文。 DOM 上下文(或页面上下文)是沙盒化的,只能通过 evaluate()
访问。 evaluate()
采用在页面中计算的函数,因此内部代码不能引用在其外部定义的任何变量或函数。
signature of Nightmare's evaluate()
function是以下内容:
function evaluate(func, callback/**, arg1, arg2...*/)
这意味着附加值可以作为附加参数直接传递给函数。 func
, callback
和arg1
, arg2
, ...通过phantomjs-node传递(它被 Nightmare 用来实际与 PhantomJS 交互)和 func
, arg1
, arg2
, ... 然后被传递给 PhantomJS's evaluate()
.
Note: The arguments and the return value to the
evaluate
function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.Closures, functions, DOM nodes, etc. will not work!
正确的用法是:
var tag = "body";
new Nightmare()
.goto(baseURL)
.evaluate(function(innertag) {
return document.querySelector(innertag).className;
}, function(className) {
className.should.equal(expected);
callback();
}, tag)
.run();
关于javascript - PhantomJS 传递参数来评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514510/