【问题标题】:Headless Browserify JavaScript Testing with Phantom.js使用 Phantom.js 进行无头 Browserify JavaScript 测试
【发布时间】:2015-02-28 23:35:17
【问题描述】:

我正在尝试找到一种方法来执行以下步骤。

  • 为浏览器编写 Node.js 代码
  • 用 browserify 编译代码
  • 在终端测试浏览器代码

我很想获得浏览器收到的console.logs,但在终端内。这不仅可以节省我的时间(从创建 HTML 文件、运行服务器、打开浏览器),还可以在部署前进行自动测试等很酷的事情。

我正在尝试制作一个名为headless-test.jsphantomjs 脚本,该脚本将使用system.args[1]fs.read 传递参数,可以获取您传递给它的任何javascript 的内容。

var content = fs.read(system.args[1])
page.content = '<html><body><script type="text/javascript">'+content+'</script></body></html>'

这将允许我做这样的事情:

phantomjs ./headless-test.js ./bundle.js

我收到了这个错误SyntaxError: Multiline comment was not closed properly,所以请确保你丑化了你的bundle.js

如果我能让这个演示在下面运行,所有这一切都将是惊人的。最小可行产品:

var system = require("system")
var webPage = require('webpage')
var page = require('webpage').create()
page.content = '<html><body><script type="text/javascript">console.log("hello world")</script></body></html>';

page.onConsoleMessage = function(msg, lineNum, sourceId) {
  console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

page.evaluate(function(){

})

phantom.exit();

这里的预期结果是:

$ phantomjs ./headless-test.js
hello world

但是我没有收到来自幻影的stdout

【问题讨论】:

    标签: javascript testing phantomjs browserify headless-browser


    【解决方案1】:

    如果你给 page.content 赋值,它会立即被计算,但之后你会从页面上下文中注册到 console.log()。您只是错过了页面中脚本元素中的console.log()

    page.content 赋值移到page.onConsoleMessage 函数之后。

    【讨论】:

      【解决方案2】:
      var system = require("system")
      var webPage = require('webpage')
      var page = require('webpage').create()
      
      page.onConsoleMessage = function(msg, lineNum, sourceId) {
        console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
      }
      
      var fs = require("fs")
      var content = fs.read(system.args[1])
      page.content = '<html><body><script type="text/javascript">'+content+'</script></body></html>'
      
      phantom.exit();
      

      【讨论】:

        【解决方案3】:

        我为此做了一个节点工具:https://github.com/mantoni/phantomic

        如果您还想使用 Mocha 作为测试框架,请尝试 Mochify (https://github.com/mantoni/mochify.js)。它使用phantomicbrout 将控制台输出正确地输入终端。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-10-13
          • 2015-02-08
          • 2012-06-11
          • 1970-01-01
          • 1970-01-01
          • 2016-04-24
          • 1970-01-01
          相关资源
          最近更新 更多