javascript - PhantomJS 传递参数来评估

标签 javascript node.js phantomjs nightmare

我有一个小型测试应用程序,它使用 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, callbackarg1, 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/

相关文章:

node.js - 将音频文件从 Google Drive 流式传输到 Discord 语音 channel

angularjs - 无法使用 phantomjs 运行 Protractor 测试

javascript - 单击带有 phantom.js 的链接并检索文档 html

javascript - 使 select2 框足够宽以容纳内容

javascript - 从下拉菜单中的数组中取回特定项目

javascript - 使用 GitHub API 编辑提交消息并将其添加到文件

javascript - 从不同的函数访问变量而不创建全局变量

javascript - 将数据动态添加到 Highcharts 中的系列

javascript - jasmine mockDate 总是休息一个月

javascript - 请求 npm : Handling Redirects