Path: blob/master/6-Selenium/phantomjs/examples/run-qunit.js
164 views
var system = require('system');12/**3* Wait until the test condition is true or a timeout occurs. Useful for waiting4* on a server response or for a ui change (fadeIn, etc.) to occur.5*6* @param testFx javascript condition that evaluates to a boolean,7* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or8* as a callback function.9* @param onReady what to do when testFx condition is fulfilled,10* it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or11* as a callback function.12* @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.13*/14function waitFor(testFx, onReady, timeOutMillis) {15var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timout is 3s16start = new Date().getTime(),17condition = false,18interval = setInterval(function() {19if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {20// If not time-out yet and condition not yet fulfilled21condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code22} else {23if(!condition) {24// If condition still not fulfilled (timeout but condition is 'false')25console.log("'waitFor()' timeout");26phantom.exit(1);27} else {28// Condition fulfilled (timeout and/or condition is 'true')29console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");30typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled31clearInterval(interval); //< Stop this interval32}33}34}, 100); //< repeat check every 250ms35};363738if (system.args.length !== 2) {39console.log('Usage: run-qunit.js URL');40phantom.exit(1);41}4243var page = require('webpage').create();4445// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")46page.onConsoleMessage = function(msg) {47console.log(msg);48};4950page.open(system.args[1], function(status){51if (status !== "success") {52console.log("Unable to access network");53phantom.exit(1);54} else {55waitFor(function(){56return page.evaluate(function(){57var el = document.getElementById('qunit-testresult');58if (el && el.innerText.match('completed')) {59return true;60}61return false;62});63}, function(){64var failedNum = page.evaluate(function(){65var el = document.getElementById('qunit-testresult');66console.log(el.innerText);67try {68return el.getElementsByClassName('failed')[0].innerHTML;69} catch (e) { }70return 10000;71});72phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0);73});74}75});767778