...

/

Miscellaneous Techniques

Miscellaneous Techniques

Explore more about Selenium debugging by learning advanced techniques.

Take a screenshot

Another way of debugging is to take a screenshot of the current browser window when an error/failure occurs. Selenium supports this in a very easy way:

var fs = require('fs');    
driver.takeScreenshot().then(function(data) {
  // Base64 encoded png
  fs.writeFileSync(__dirname + "/tmp/screenshot1.png", data, 'base64');      
});

However, there is one problem with the above script. When the above script runs for the second time, it will return an error The file already exists. So, a simple workaround is to write a file with the timestamped file name as:

Press + to interact
// save to timestamped file, e.g. screenshot-12070944.png
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(), !mm[1] && '0', mm, !dd[1] && '0', dd].join('');
};
function writeScreenshot(data) {
name = new Date().yyyymmdd() + ".png";
var screenshotPath = __dirname + "/tmp/";
var fs = require('fs');
fs.writeFileSync(screenshotPath + name, data, 'base64');
};
test.it("Take screenshot saved to timestamped file", function() {
driver.takeScreenshot().then(function(data) {
writeScreenshot(data);
});
});

Testing the recipe

Practice the screenshot code ...