PhantomJS - 测试
PhantomJS 为网页提供了大量 API,可提供所有详细信息。PhantomJS 可用于测试,如获取页面内容、进行屏幕共享、将页面转换为 pdf 等。市场上有许多流行的测试库,可与 PhantomJS 一起使用并用于测试。
一些可与 PhantomJS 配合使用的流行框架如下 −
- Mocha
- Jasmine
- Qunit
- Hiro
- Laika
- Buster.JS
- WebDriver
示例 - PhantomJS 与 Qunit
(function () { var url, timeout,args = require('system').args, page = require('webpage').create(); url = args[1]; timeout = parseInt(10, 10); page.onConsoleMessage = function (msg) { //打印所有控制台消息 console.log(msg); }; page.onInitialized = function () { // 在页面初始化时调用 page.evaluate(callqunit); }; page.onCallback = function (message) { // called from var result, failed; if (message) { if (message.name === 'QUnit.done') { result = message.data; failed = !result || !result.total || result.failed; if (!result.total) { console.error('No tests were executed'); } pageexit(failed ? 1 : 0); } } }; page.open(url, function (status) { // opening page if (status !== 'success') { console.error('Unable to access network: ' + status); pageexit(1); } else { var checkqunit = page.evaluate(function () { //评估页面并检查是否为 qunit 对象 is present on the given page url return (typeof QUnit === 'undefined' || !QUnit); }); if (checkqunit) { console.error('Qunit scripts are not present on the page'); pageexit(1); } //使用 10 秒的超时时间,否则将打印来自控制台的消息。 setTimeout(function () { console.error('The specified timeout of ' + timeout + ' seconds has expired. Aborting...'); pageexit(1); }, timeout * 1000); } }); function callqunit() {
qunit.html
<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width"> <title>QUnit Example</title> <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-2.3.2.css"> </head> <body> <div id = "qunit"></div> <div id = "qunit-fixture"></div> <script src = "https://code.jquery.com/qunit/qunit-2.3.2.js"></script> </body> </html>
输出
命令 − phantomjs qunit.js http://localhost/tasks/qunit.html
上述程序生成以下输出。
{"passed":3,"failed":2,"total":5,"runtime":23} Time taken is 23ms to run 5 tests. 3 passed, 2 failed.