Tips and Tricks

Random list of useful things

What development branch are we on?

Example for Mercurial but could easily be adapted for git, svn, etc.

    require("execSync").exec("hg branch").stdout.replace(/\n|\r/g, "");                

What machine are we running on?


Maximise the browser window


Compare numbers with tolerance

Different answers between test runs are not always wrong, if you have a known tolerance for differences.

This extends the number prototype to compare numbers to within 1%:

    Number.prototype.roughly = function (comparedTo) {
        if (this == comparedTo) {
            return true;
        var diff = ((Math.abs(comparedTo - this)) / this) || 1;
        return (diff < 0.01);

        "Value mismatch in latest run!");

Get User's home directory cross-OS

    var HOME = (process.platform.match(/win32/) 
        ? process.env["USERPROFILE"] 
        : process.env["HOME"]).replace(/\\/g, "/");

Select elements only if visible

Using CSS property selectors you can select visible elements or elements that are inside a visible container.

e.g. a locator for specific class of icon in a modal dialog that can have one of a choice of divs showing

    div[style*='display: block'] li[tooltip='Chart']

Check for a broken image

If you have an image with a broken link, your users will just see an ugly icon.

You can check that an image is present by getting its naturalWidth property (supported by browsers and IE11).

    assert($("span[ng-show=''] img", 1).getAttribute("naturalWidth"),
        "PDF icon missing");


Pull data from a text file in slices

    //in this example I want to fill a comments array
    //with the first 100 characters
    //then the next 200
    //then the next 300 and so on up to 1000 characters
    var comments = [];
    var comment;
    var buffer = new Buffer(1024);
    var lastPosition = 0;
    var commentsFile = fs.openSync(testing.TEST_HOME + "Comments/Aeneidos.txt", "r");
    for (var i = 1; i <= 10; i++) {
        fs.readSync(commentsFile, buffer, 0, 100 * i, lastPosition);
        comment = buffer.toString().slice(0, 100*i);
        lastPosition += 100*i;

Capture screenshots

    //assuming HOME is the root for npm modules
    var OutputType = require(HOME + "/node_modules/webdriver-sync/src/interfaces/OutputType.js");
    if (driver.getScreenshotAs) {
        var screenshot = driver.getScreenshotAs(OutputType.BASE64);
        fs.writeFileSync(HOME + "/screenshots/UniqueScreenshotName.png",
            screenshot, "base64");

Run commands on a remote (linux) server

You might need to control the web server to set up the test environment or poll a log to check server side progress or errors.

To avoid having to enter an ssh password every time, set up an ssh key.

On Windows, download and run the full putty installer to get the plink ssh client.

    function ssh(commands, user, host) {
        if (typeof commands == "string") {
            commands = [commands];
        console.log("SSH to " + host);

        var sshCall;
        if (process.platform.match(/win32/)) {
            sshCall = require("child_process").spawnSync(
                    ["-ssh", "-pw", "Y0rPassW0rd!",
                    user + "@" + host, 
                    commands.join("; ")]
        } else {
            sshCall = require("child_process").spawnSync(
                    [user + "@" + host, 
                    commands.join("; ")]
        try {
            if (sshCall.stderr.length) {
                console.error("SSH FAILED " + sshCall.stderr.toString());
                return sshCall.stderr.toString();
        } catch (e) {
        return sshCall.stdout.toString();

    log.startCase("Check no invalid files are left in the upload folder");
    assert(!ssh("ls /home/tomcat/ROOT/uploads", true).length,
        "Bad files left in the upload folder");

    var sh = require("child_process").execSync;

    function taillog(n, reverse) {
        n = n || 10;
        console.log("FETCHING LAST " + n + " LINES OF THE LOG");
        var tailedLog = sh.exec("ssh tester@" + + " \" tail -n " + n 
            + " /var/log/tomcat7/AUT.log\"").stdout;
        //if you are looking for specific messages by regex matching
        //you might want to reverse the order so the last messages 
        //appear first
        if (reverse) {
            tailedLog = tailedLog.split(/\n/).reverse().join("\n");             
        //return the log as a String object augmented with a "top" method
        //for getting the earliest (or latest if reversed) messages
        tailedLog = new String(tailedLog); = function tailTop(lineCount) {
            return this.split(/\n/).slice(0,lineCount).join();
        return tailedLog;

    aggregationLog = taillog(5, true);
    //last line could be blank, so check last 2 for completion message
    while (! running server-side job complete/)) {
        //do something else, such as check for errors in the other 3 lines

    function greplog(greppee, count, reverse) {
        console.log("GREPPING LOG FOR '" + greppee + "'");
        var greppedLog = sh.exec("ssh tester@" + + " \" grep '" + greppee 
            + "' /var/log/tomcat7/AUT.log\"").stdout;
        if (count) {
            greppedLog = greppedLog.split(/\n/).slice(-count).join("\n");
        if (reverse) {
            greppedLog = greppedLog.split(/\n/).reverse().join("\n");
        return greppedLog;//will be empty (false) if the greppee phrase is not found

    function MYSQL_dump() {
        var dumpCMD = "mysqldump --user=testuser --max_allowed_packet=1G --host=" + host 
        + " --port=3306 --default-character-set=utf8 \"testdb\" -ptestPassword > " 
        +  "dumps/" + host.split(/\./)[0] + "_DBdump.sql";
        return sh.exec(dumpCMD);

Testing session timeouts

Assuming your session lifetime is controlled by a cookie, then it's simply a case of:

    //start a session
    //do stuff
    //now test the session has timed out

CSS audits

If you use a 3rd-party CSS framework, you will end up shipping a lot of styles you don't use. You might also want to limit the number of fonts and font-sizes to stop your site looking a mess. Webdriver can run a javascript routine in the browser's console to produce a quick CSS audit. This can be easily extended to look for other CSS properties.

function PTL_cssAudit() {
    var cssTally = 
        'var used = 0; ' +
        'var count = 0;' +
        'var tallies = {' +
            '"fontSize": {},' +
            '"fontFamily": {},' +
            '"color": {},' +
            '"backgroundColor": {}' +
        '};' +

        ' [], function (styleSheet) {' +
            'styleSheet.rules && [], function (rule) {' +
                'if ( {' +
                    '(rule.selectorText|| "").split(/, /).forEach(function (selector) {' +
                        'count++; ' +
                        'if (selector && !selector.match(/:/) ' +
                            '&& document.querySelectorAll(selector).length) {' +
                            'used++;' +
                            'for (var tally in tallies) {' +
                                'if ([tally] && ([tally] != "inherit")) {' +
                                    'tallies[tally][[tally]] = ' +
                                        'tallies[tally][[tally]] || [];' +
                                    'tallies[tally][[tally]].push(rule.selectorText);' +
                                '}' +
                            '}' +
                        '}' +
                    '});' +
                '}' +
            '});' +
        '});' +
        'tallies.count = count;' +
        'tallies.used = used;' +
        'tallies.usage = Math.floor(100*used/count);' +
        'return JSON.stringify(tallies);';
    var audit = browser.executeScript(cssTally);
    return JSON.parse(audit);

Check for duplicate ids

log.startCase("Checking for duplicate element ids");
assert(!$("[id]").map(function (e) {
        return e.getAttribute("id");
    }).filter(function(e,i,a) {
        return ((a.lastIndexOf(e) !== i) && !console.log(e));
    "Duplicate ids present");

Making things stand out in console logs

Allow a string or array of strings to be wrapped in a rectangular border:

String.prototype.padded = function (finalLength) {
    //pad a string with spaces to make it finalLength long
    return (this + (new Array(120)).join(" ")).slice(0,finalLength);
Array.prototype.bordered = function (bChar) {
    //find the length of the longest string in this array
    var bWidth = this.reduce(function (a, b) { return a.length > b.length ? a : b; }).length;
    //create a line of bChars to border this string
    var bLine = (new Array(bWidth + 5)).join(bChar).slice(0,120);
    //return the array as a newline-separated string with a bChar border
    return "\n" + bLine + "\n" 
        + (a) {
            return bChar + " " + (a.padded(bWidth)) + " " + bChar;
        + "\n" + bLine + "\n";
String.prototype.bordered = function (bChar) {
    return this.split(/\n/).bordered(bChar);

POSTing JSON to the server

Often someone will tap you on the shoulder and ask if you can use your automation scripts to fill in a web-based form for them to save them having to do it hundreds of times. This is a perfectly cromulent reason to use automation but driving the front-end is fraught with danger from timing issues. A far better idea is to work out what data the page is POSTing and replicate that request directly.

There is no need to employ any external libraries or npm modules to POST data, you can use the browser itself. This has the benefit of occuring within the existing session, so you don't need to worry about spoofing credentials or cookies.

function WD_postJSON(url, payload) {
    var xhr = driver.executeScript(
        "xhr = new XMLHttpRequest();" +
        "'POST', '" + url + "', false);" +
        "xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8');" +
        "xhr.send('" + JSON.stringify(payload) + "');" +
        "return (xhr.status + '###' + xhr.responseText);"
    xhr = xhr.split("###");
    return {status: xhr[0], responseText: xhr[1]};

Dealing with iframes

Webdriver deals with iframes by switching context.

If you want the $() method to work inside an iframe rather than the page's root document, do this:

browser.switchTo().frame("frmContent");//for an iframe with id frmContent

To return to the main document:


Reading resource headers

Let's assume you bundle your javascript to reduce request counts, want to ensure it is being gzipped but the name of the javascript resource changes between builds so that the browser does not fall back to the cached version when your javascript is updated

You can query the page itself to find the current URL for the javascript bundle, request it separately and check its headers:

function getHeaders(url, specificHeader) {
    var xhr_headers = driver.executeScript(
        "xhr = new XMLHttpRequest();" +
        "'GET', '" + url + "', false);" +
        "xhr.setRequestHeader('Accept-Encoding', 'gzip');" +
        "xhr.send();" +
        (specificHeader ? 
            "return xhr.getResponseHeader('" + specificHeader + "');" : 
            "return xhr.getAllResponseHeaders();")
    return xhr_headers;

log.startCase("Check javascript bundle is gzipped");
var firstJS = browser.executeScript("return document.scripts[0].src;");
var CEheader = PTL.getHeaders(firstJS, "Content-Encoding");
assert(CEheader == "gzip", "gzip not enabled");

Using a proxy server

You might want to use a proxy server while you are testing, for instance to run the tests past OWASP ZAPROXY for additional security testing. You can do this in Firefox by editing the Profile and in Chrome via the ChromeOptions object:

    var wd = require("webdriver-sync");
    var profile = new wd.FirefoxProfile();
    profile.setPreference("network.proxy.http", "");
    profile.setPreference("network.proxy.http_port", 8080);
    profile.setPreference("network.proxy.type", 1);//set to manual

    var driver = new wd["FirefoxDriver"](profile);       

    //or in Chrome:
    var chromeOptions = new wd.ChromeOptions();
    var caps = new wd.DesiredCapabilities["chrome"]();
    caps.setCapability("chromeOptions", chromeOptions);

    var driver = new wd["ChromeDriver"](caps);    

Using ZAP proxy server in testing

ZAP has a JSON API we can use during testing. We cannot use the XHR object in the browser because the ZAP server is not the same domain as the AUT, so we run wget as a child process and save the responses to a temporary file.

These are some routines to start a new ZAP session (call this at the start of your test script) and 2 routines to return a summary or a detailed breakdown of every HTTP request logged during the test:

    var sh = require("child_process").execSync;
    var fs = require("fs");

    function WD_zapGET(URL) {//helper routine for the methods below
        var zapTemp = "ZAPtemp.json";
        sh(`wget -O ${zapTemp} "${URL}"`);
        var zapResponse = fs.readFileSync(zapTemp).toString(); 
        return JSON.parse(zapResponse);         
    function WD_zapSession(baseURL) {//create a new test session
        //cannot use getJSON due to CORS, so use wget
        var zapResponse = WD_zapGET(
            "Could not start ZAP session");
    function WD_zapRequestSummary(baseURL) {//request summary from test session
        var zapResponse = WD_zapGET(
        //id, url, status code, method, time
        return zapResponse.urlsByRequestRegex;
    function WD_zapRequestDetail(baseURL, start, count) {//full requests and responses from test session
        start = start || "";
        count = count || "";
        var zapResponse = WD_zapGET(
        //id, requestHeader, requestBody, cookieParams, responseHeader, responseBody
        return zapResponse.messagesByRequestRegex;

Useful Sublime Text plugins

  • Package Control - look for all the others here
  • Alignment
  • All Autocomplete
  • ColorPicker
  • Git
  • GitGutter
  • Github Color Theme
  • HTML-CSS-JS Prettify
  • Javascript & NodeJS Snippets
  • JSHint Gutter
  • Mercurial
  • Modific
  • Node Completions
  • SideBarEnhancements
  • Sublime REPL
  • SubliMerge Pro
  • Terminal

Note that to get JSHint Gutter to play nicely with ES6 (e.g. template strings), you need to copy or symlink the latest jshint npm module from /usr/lib/node_modules/jshint to ~/.config/sublime-text-3/Packages/JSHint Gutter/scripts/node_modules/jshint (or equivalent for your OS).