Search⌘ K
AI Features

Miscellaneous Techniques

Explore various debugging techniques for Selenium WebDriver test scripts, including taking screenshots on failures, keeping browsers open for inspection, and running selected test steps against an existing browser session to speed up troubleshooting and enhance test reliability.

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:

Javascript (babel-node)
// 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 ...