使用Phantom.js进行无头Browserify JavaScript测试

Headless Browserify JavaScript Testing with Phantom.js

本文关键字:Browserify JavaScript 测试 Phantom js 使用      更新时间:2023-09-26

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

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

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

我正在尝试使一个名为headless-test.js的东西成为一个phantomjs脚本,该脚本将使用system.args[1]fs.read传递参数

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

如果您将某个值分配给page.content,则会立即对其求值,但之后您将从页面上下文注册到console.log()。您只是错过了页面中script元素中的console.log()

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

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();

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

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