Debugging by Printing Texts
This lesson explores how to debug a Selenium test script by printing texts.
We'll cover the following...
Debugging
Debugging means analyzing and removing bugs from the code. In the context of automated functional testing, debugging is a way to find out why a test step did not execute as expected and how we can fix it.
Print text for debugging
A common and widespread tactic of debugging is to print out texts (console.log
statements) ...
...
driver.get("file://" + __dirname + "/../../site/assert.html");
driver.getTitle().then(function(page_title){
console.log("Now on page: " + page_title);
});
driver.findElement(By.id("app_id")).getText().then(function(appNo){
console.log("Application number is " + appNo);
});
The output from executing the above scripts would be:
Now on page: Assertion Test Page
Application number is 1234
However, for complex objects, the output in the default string format might not be meaningful. So, we can convert dump it in JSON format as:
console.log(JSON.stringify(complexObject));
Furthermore, when a test is executed in a Continuous Integration server, the output is typically captured and shown. This can be quite helpful in debugging test execution.
Write page source or element HTML to a file
Printing out text is helpful while working with the shorter texts, however, this approach fails when dealing with the larger texts, such as the page source, etc. So, a better approach would be to write the output in a temporary file and inspect it later. We can do so by running the following scripts:
var output_file = __dirname + "/tmp/login_page.html";
var fs = require('fs');
// console.log(output_file);
driver.getPageSource().then(function(page_source){
fs.writeFile(output_file, page_source, function(err) {
if (err) {
return console.log(err)
}
console.log("Saved to file: " + output_file)
});
});
Similarly, we can just dump a specific part of the web page as:
var elem = driver.findElement(By.id("div_parent"));
driver.executeScript("return arguments[0].outerHTML;", elem).then(function(elem_html) {
fs.writeFile(__dirname + "/tmp/login_parent.xhtml", elem_html);
});
Testing the recipe
The following recipe runs the above scripts one-by-one in a Headless Chrome browser. Click the Run button to execute the test script.