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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Configure, Customize, and Use Ballerina Logs
  • Alexa Skill With Local DynamoDB
  • Enhance User Experience With a Formatted Credit Card Input Field
  • Enhancing Java Application Logging: A Comprehensive Guide

Trending

  • Proactive Security in Distributed Systems: A Developer’s Approach
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Infrastructure as Code (IaC) Beyond the Basics
  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.

By 
Alan Richardson user avatar
Alan Richardson
·
Aug. 18, 16 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.8K 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
    • Alexa Skill With Local DynamoDB
    • Enhance User Experience With a Formatted Credit Card Input Field
    • Enhancing Java Application Logging: A Comprehensive Guide

    Partner Resources

    ×

    Comments
    Oops! Something Went Wrong

    The likes didn't load as expected. Please refresh the page and try again.

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • 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:

    Likes
    There are no likes...yet! 👀
    Be the first to like this post!
    It looks like you're not logged in.
    Sign in to see who liked this post!