Over a million developers have joined DZone.

How to Debug WebDriver JavascriptExecutor in Java

JavascriptExecutor requires us to learn JavaScript, use the Browser Console, and check our locator assumptions using FirePath.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

A common theme when debugging WebDriver code is the need to jump between breakpoints, evaluate, and browser dev tools.

And we shall do exactly that in this how to when we look at debugging JavascriptExecutor. This is a hypothetical set of actions built around a sample test I was sent by a blog reader. And, I’m walking through a debug process to illustrate some points. It is not the most efficient debug process, but very often, we don’t know what the problem is, so our process isn’t efficient. And when you start working with a ‘block of existing code’ it often is not efficient.

Assume we have this test:

private static WebDriver driver;

@Before
public void setDriver() {
    driver = new FirefoxDriver();
}

@Test
public void inputText() throws Exception {
    driver.get("http://compendiumdev.co.uk/selenium/testpages/html5_html_form.html" );

    WebElement textField = driver.findElement(By.name("number_field"));

    writeText(textField, "");
    Assert.assertEquals("", textField.getAttribute("value"));
    writeText(textField, "35");
    Assert.assertEquals("35", textField.getAttribute("value"));

    driver.findElement(By.id("submitButton")).click();
    Assert.assertEquals("35", driver.findElement(By.id("_valuenumber_field")).getText());
}

public void writeText(WebElement textField, String text) {
    ((JavascriptExecutor) driver).executeScript("arguments[0].value='" +
            text + "';", textField);
}


And it doesn’t work. The second Assertfails, so we suspect probably something wrong with the JavaScript, but we didn’t get an error, so it isn’t a syntax error.

What do we do?

Well, we could hack about a bit with the writeText method and change the Javascript.

public void writeText(WebElement textField, String text) {
    //((JavascriptExecutor) driver).executeScript("arguments[0].value='" +
    //        text + "';", textField);
    ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute=('value','" +
                    text + "';", textField);
}


Nope, that gives a syntax error on the JavaScript.

I’ll rewrite that method to make it a little easier to read:

public void writeText(WebElement textField, String text) {

    String js;
    JavascriptExecutor exec = (JavascriptExecutor) driver;

    //js = String.format("arguments[0].value='%s';",text);
    //exec.executeScript(js, textField);

    js = String.format("arguments[0].setAttribute=('value','%s';",text);
    exec.executeScript(js, textField);
}


Note: This is now much easier for me to breakpoint, debug, and evaluate, but I don’t think I’ll learn much here by doing that.

And, the code is now more readable and it's obvious what the syntax error is... I left off a ‘)’.

So I’ll fix the syntax error. And…

js = String.format("arguments[0].setAttribute=('value','%s');",text); 


Yeah, and that’s not how you call setAttribute…

OK. Time to stop hacking about in Java and start debugging.

First Use the Console

First I’m going to execute the JavaScript in the console.

That means rewriting it.

I find the element using By.name in Java, so I’ll use the console and type:

document.getElementsByName("number_field")[0]

That is equivalent to the findElement(By.name("number_field"))

And it shows me:

<input type="number" value="12" name="number_field">

Which is the same as the input field on screen which defaults to 12.

So, I’ll set the value using setAttribute

document.getElementsByName("number_field")[0].setAttribute('value','13'); 


Then check that the attribute is set

document.getElementsByName("number_field ")[0].value 


And the console tells me “13” but the GUI stills says “12”.

Hmmm…

Thinking that I should use ‘value’ instead, just in case, I’ll try.

document.getElementsByName("number_field")[0].value='14'; 


And then check it was set:

document.getElementsByName("number_field ")[0].value 


And the console tells me “14” but the GUI stills says “12”.

OK.

Let me check first assumptions and check the locator.

Using FirePath in Firefox:

[name="number_field"]

Oh. FirePath is showing me two fields with that name, both with a default value of ‘12’.

And the one I want is the second one.

Let me just try that JavaScript again.

document.getElementsByName("number_field")[1].value='15'; 


And that changed it on the GUI as well.

So I’ve found my problem.

Model the Console JavaScript in the Java Code

First I’ll change the JavaScript method to be equivalent to what I did above.

public void writeText(WebElement textField, String text) {

    String js;
    JavascriptExecutor exec = (JavascriptExecutor) driver;

    js = String.format("arguments[0].value='%s';",text);
    exec.executeScript(js, textField);
}


And then I’ll change how I locate the element:

WebElement textField = driver.findElements(By.name("number_field")).get(1); 


Which is actually pretty close to what I wrote in JavaScript.

And try the @Test

And it worked.

At this point, I might want to try and refactor the locator to avoid a findElements but if that isn’t possible, I’ll leave it as it is. (for now).

But I’ll add a comment:

/* there are two inputs named “number_field” the first in a non-displayed, prototype form */

And either amend the web page or raise a bug against the system.

We were slightly unlucky that the non-displayed form had the same value in the “number_field: as the main form. Otherwise, an early assertion on the value of the found element might have revealed the problem early in the code. But my real problem stemmed from inspecting the element, but not running the locator through FirePath. I didn’t test the locator early enough.

Summary

When working with JavascriptExecutor:

  • Write the JavaScript code with String.format because string concatenation makes it hard to read
  • Run your code in the console (you might have to amend it a bit)
  • Check results in the console

When working with WebDriver:

  • Check your assumptions (locators) by running the same locator in FirePath or Chrome ‘find’
  • When coding, if you aren’t writing Unit tests (and very often when we work with WebDriver we don’t):

    • Run your code as early as you can, to avoid writing a lot of code that you have to debug
    • Write code simply, e.g. inline, then ‘extract to method’ when it is working
    • Assert often, you can always remove redundant and irrelevant asserts early

    Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

    Topics:
    javascript ,java ,web driver ,javascriptexecutor

    Published at DZone with permission of Alan Richardson, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    The best of DZone straight to your inbox.

    SEE AN EXAMPLE
    Please provide a valid email address.

    Thanks for subscribing!

    Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
    Subscribe

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}