JavaScript with Selenium

This demo will show JavaScript being used as the element locators inside the methods used in the Page Objects. During the demo you will see the Selenium test cases navigating around JavaScript enabled pages, clicking buttons, entering text/selecting text and entering a date.

NOTE: The test execution has been slowed down for demo purposes

 

Occasionally while creating Selenium test cases you will come across web elements that use JavaScript events such as hover, mouseover or mousedown in order to display hidden elements. In your test cases you could attempt to use a technique such as action builders in your selenium code to deal with these type of JavaScript events, or you could use JavaScript inside of your Selenium code to fire these JavaScript events.

Below is an example of a web element that uses a JavaScript hover event to display a pop up dialog.

before

 

After hovering over the paragraph with the mouse a JavaScript event is fired to display the pop up dialog.

after

 

Example Code:

package com.demo.test;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.support.ui.Sleeper;
import org.testng.annotations.Test;

public class JqueryExampleTests extends CommonMethodsPage {

    @Test
    public void buttonTests() throws InterruptedException {

        // And now use this to visit jQuery examples
        driver.get("http://jqueryui.com/resources/demos/tabs/default.html");
        Sleeper.sleepTight(SMALL_DELAY);

        // Click Proin dolor Button
        javascriptExecutor.executeScript("$(\".ui-tabs-anchor:contains('Proin dolor')\").click()");
        Sleeper.sleepTight(SMALL_DELAY);

        // Implicitly wait and assert the correct data shows
        driver.manage().timeouts().implicitlyWait(WAIT_SECONDS, TimeUnit.SECONDS);
        assertTrue(StringUtils.contains(driver.getPageSource(), "Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa"));
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

    }

}

Leave a Reply

Download and extend ATF...

ATF Is Now Open Source

Join this 10 week program anytime...

DevOps Mastery Program

Get your DevOps health check now...

Free DevOps Assessment

X