Skip to main content
blog title image

5 minute read - Selenium WebDriver FAQs Test Automation

How to Debug WebDriver JavascriptExecutor in Java

Aug 17, 2016

TLDR; JavascriptExecutor requires us to learn JavaScript and use the Browser Console, and check your locator assumptions using FirePath

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("https://testpages.herokuapp.com/styled/basic-html-form-test.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 is obvious what the syntax error is, I missed 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