Selenium Webdriver (node.js) take screenshot and save test results

Just for the record, this is how you take a screenshot with WebdriverJS:

var webdriverjs = require('webdriverjs'),
    client = webdriverjs.remote({
        desiredCapabilities: {
            browserName: 'chrome'
        }
    });

client
    .init()
    .url('http://google.com')
    .saveScreenshot(__dirname + '/googleScreenshot.png')
    .end();

You can also use WebdriverCSS to take screenshots. It is a plugin for WebdriverJS to do CSS regression tests. It is pretty much the same like PhantomCSS.


Adapting aychedee's answer into a complete promise that will resolve after the file is written and reject on write failure:

const util = require('util')
const fsp = require('fs').promises

function takeScreenshot(driver, file){
  return driver.takeScreenshot()
    .then(image => fsp.writeFile(file, image, 'base64'))
}

Or in an async function

async function takeScreenshot(driver, file){
  let image = await driver.takeScreenshot()
  await fsp.writeFile(file, image, 'base64')
}

For saving the test logs you typically use a test runner. When you check if an element is on the page and you can't find it then you raise an exception (typically an assertion error) and the test runner will record this and mark it as a failed test. In the documentation they suggest you use Mocha.

As for saving a screenshot to disk, the the api looks like this

driver.takeScreenshot().then(
    function(image, err) {
        require('fs').writeFile('out.png', image, 'base64', function(err) {
            console.log(err);
        });
    }
);