DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How to Configure, Customize, and Use Ballerina Logs
  • Deploying Salesforce and Heroku Apps with Ease
  • Alexa Skill With Local DynamoDB
  • Celesta: SQL Database APIs, Schema Migration, and Testing in a Single Java Library

Trending

  • Revolutionizing Software Testing
  • Designing Databases for Distributed Systems
  • Agile Estimation: Techniques and Tips for Success
  • Monkey-Patching in Java
  1. DZone
  2. Coding
  3. Languages
  4. How to Debug WebDriver JavascriptExecutor in Java

How to Debug WebDriver JavascriptExecutor in Java

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

Alan Richardson user avatar by
Alan Richardson
·
Aug. 18, 16 · Tutorial
Like (1)
Save
Tweet
Share
4.40K Views

Join the DZone community and get the full member experience.

Join For Free

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
    Debug (command) Java (programming language) code style unit test JavaScript Console (video game CLI)

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

    Opinions expressed by DZone contributors are their own.

    Related

    • How to Configure, Customize, and Use Ballerina Logs
    • Deploying Salesforce and Heroku Apps with Ease
    • Alexa Skill With Local DynamoDB
    • Celesta: SQL Database APIs, Schema Migration, and Testing in a Single Java Library

    Comments

    Partner Resources

    X

    ABOUT US

    • About DZone
    • Send feedback
    • Careers
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • support@dzone.com

    Let's be friends: