Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to the search button without entering a return date.

public class Callender {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\selenium\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.abhibus.com/");
        //to select leaving from
        WebElement source =driver.findElement(By.xpath("//*[@id='source']"));
        source.clear();
        source.sendKeys("Tenal");
        Thread.sleep(2000);
        source.sendKeys(Keys.ENTER);
        //to select destination
        WebElement destination =driver.findElement(By.xpath("//*[@id='destination']"));
        destination.clear();
        destination.sendKeys("Hyderaba");
        Thread.sleep(2000);
        destination.sendKeys(Keys.ENTER);


        WebElement element = driver.findElement(By.xpath("//*[@id=\"datepicker1\"]"));
        String journeydate="04-10-2019";
        selectJourney(driver,element,journeydate);

        Thread.sleep(3000);
        WebElement element1 = driver.findElement(By.xpath("//*[@id=\"datepicker2\"]"));
        String returndate="06-10-2019";
        selectRJourney(driver,element1,returndate);
        //to click search button
        driver.findElement(By.xpath("//*[@id=\"roundTrip\"]/a")).click();
    }
    public static void selectRJourney(WebDriver driver, WebElement element1, String returndate) {
        JavascriptExecutor je=(JavascriptExecutor)driver;
        je.executeScript("arguments[0].setAttribute('value','"+returndate+"');", element1);
        // TODO Auto-generated method stub

    }
    public static void selectJourney(WebDriver driver,WebElement element,String journeydate) {
        JavascriptExecutor js= (JavascriptExecutor)driver;
        js.executeScript("arguments[0].setAttribute('value','"+journeydate+"');",element);
    }

Would appreciate any insights or assistance in identifying what may have gone wrong or what steps I could potentially be overlooking?

Answer №1

Kindly utilize the following code snippet to set the calendar value by using

document.getElementById('datepicker1').value = "Your_Date"
.

String journeydate="04-10-2019";
selectJourneyDate(driver,journeydate);

Thread.sleep(3000);
String returndate="06-10-2019";
selectReturnJourneyDate(driver,returndate);

Code Modification:

public static void selectReturnJourneyDate(WebDriver driver, String returndate) {
    JavascriptExecutor je=(JavascriptExecutor)driver;
    je.executeScript("document.getElementById('datepicker2').value = '"+returndate+"';");

}
public static void selectJourneyDate(WebDriver driver,String journeydate) {
    JavascriptExecutor je=(JavascriptExecutor)driver;
    je.executeScript("document.getElementById('datepicker1').value = '"+journeydate+"';");

}

Recommendations:

  • Consider using id instead of xpath.

  • Avoid using JavascriptExecutor for real testing purposes.

  • Merge selectReturnJourneyDate and selectJourneyDate into a single method as they share similar code logic.

********************** EDITED *************************

String journeydate="04-10-2019";
pickDateFromCalendar(driver,"datepicker1",journeydate);

Thread.sleep(3000);
String returndate="06-10-2019";
pickDateFromCalendar(driver,"datepicker2",returndate);

You can create a generic method pickDateFromCalendar and pass the date picker id as an argument:

public static void pickDateFromCalendar(WebDriver driver, String datePickerId, String selectedDate) {
    JavascriptExecutor je=(JavascriptExecutor)driver;
    je.executeScript("document.getElementById('"+datePickerId+"').value = '"+selectedDate+"';");

}

***** HACK AS PER YOUR LEAD REQUIREMENT ******

driver.findElement(By.id("datepicker1")).click();
int currentSelectedDate = Integer.parseInt(driver.findElement(By.cssSelector(".ui-state-highlight")).getText());
driver.findElement(By.cssSelector(".ui-state-highlight")).click();
driver.findElement(By.id("datepicker2")).click();
if(currentSelectedDate>=30)
    driver.findElement(By.xpath("//a[@class='ui-state-default'][contains(text(),'1')]")).click();
else
    driver.findElement(By.xpath("//a[@class='ui-state-default'][contains(text(),'"+(currentSelectedDate+1)+"')]")).click();

Answer №2

Give this approach a try. I utilized Selenide, which takes care of the webdriver management automatically.

You have the flexibility to customize the date selection according to your requirements.

BusSearchTest.java

    package com.abhibus;

    import com.codeborne.selenide.Configuration;
    import com.codeborne.selenide.SelenideElement;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;

    import static com.codeborne.selenide.Condition.appear;
    import static com.codeborne.selenide.Condition.text;
    import static com.codeborne.selenide.Selenide.$;
    import static com.codeborne.selenide.Selenide.open;


    public class BusSearchTest {

        @DataProvider
        public static Object[][] itineraries() {
            return new String[][]{
                    {"Tenal", "Tenali", "Hyderaba", "Hyderabad", "Tenali → Hyderabad"}
            };
        }

        @BeforeTest
        public void setup() {
            Configuration.timeout = 10 * 1000;
        }

        @BeforeMethod
        public void beforeMethod() {
            open("https://www.abhibus.com/");
        }

        @Test(description = "Search Buses", dataProvider = "itineraries")
        public void busSearch(String from, String fromExpected, String to, String toExpected, String expected) {
            //to select leaving from
            $("#source").setValue(from);
            $("#ui-id-1 li.ui-menu-item")
                    .shouldHave(text(fromExpected))
                    .shouldBe(appear)
                    .click();
            //to select destination
            $("#destination").setValue(to);
            $("#ui-id-2 li.ui-menu-item")
                    .shouldHave(text(toExpected))
                    .shouldBe(appear)
                    .click();

            // from date: 04-October-2019
            $("#datepicker1").click();
            SelenideElement datePicker1 = $(".ui-datepicker-group-first");
            while (!datePicker1.find("span.ui-datepicker-month").text().trim().equals("October")) {
                $(".ui-datepicker-group-last").find("span").shouldHave(text("Next")).click();
            }
            datePicker1.findAll("tr td a").filterBy(text("4")).first().click();

            // to date: 06-October-2019
            $("#datepicker2").click();
            SelenideElement datePicker2 = $(".ui-datepicker-group-first");
            while (!datePicker2.find("span.ui-datepicker-month").text().trim().equals("October")) {
                $(".ui-datepicker-group-last").find("span").shouldHave(text("Next")).click();
            }
            datePicker2.findAll("tr td a").filterBy(text("6")).first().click();

            // click search
            $("a[title='Search Buses']").click();

            // assert search page
            $("#SubHead1way h1").shouldHave(text(expected));
        }
    }

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>tech.webisto</groupId>
        <artifactId>abhibus-tests</artifactId>
        <version>1.0-SNAPSHOT</version>
        <properties>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.2</version>
                    <configuration>
                        <source>${maven.compiler.source}</source>
                        <target>${maven.compiler.target}</target>
                        <suiteXmlFiles>
                            <suiteXmlFile>test.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <dependencies>
            <dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>7.0.0</version>
            </dependency>
            <dependency>
                <groupId>com.codeborne</groupId>
                <artifactId>selenide</artifactId>
                <version>5.2.8</version>
            </dependency>
        </dependencies>
    </project>

The repository link for the code can be found here: https://github.com/WebistoTech/AbhiBusTests.git

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

Troubleshooting issues with ASP.NET bundling and minification when using Angular.js

After reviewing many questions on the same topic, none of them were able to solve my specific case. Our current challenge involves bundling and minifying AngularJs files within .Net code. The following code snippet shows how we are bundling our files insi ...

Opening a new window with Node-Webkit's start function

My application built on node-webkit has a control window and a separate presentation window. The control window collects data and triggers the opening of the presentation window using the window.open function. Once the presentation window is open, it can ...

How can I convert a JSONArray into an Adapter for a RecyclerView in Android?

I have a question regarding my Android app. I am working with a JSONArray of objects and was wondering if it is possible to pass this directly into a recycleView adapter. Most recycleView implementations typically involve first retrieving the data from th ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added ...

Utilizing a particular iteration of npm shrinkwrap for project dependencies

When deploying my node.js app to Appfog, I encountered a problem with their install script failing to parse npm-shrinkwrap.json. The current format of a dependency in shrinkwrap.json is as follows: "async": { "version": "0.2.10", "from": " ...

Failed to retrieve UI data from localstorage while performing an asynchronous action

Whenever I click on a specific "task," it loads correctly and the correct UI with data is displayed. The issue arises when clicking on the link through the browser input window - localhost:port/task/edit/id, or when manually refreshing the page for each "t ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Triggering a loop error may occur when attempting to update the state based on a

What I want to achieve is updating the state with the value received from a child component. However, whenever I try using the setstate method in my function, it results in a looping error. Here's a snippet of my code: class ParentTab extends Compone ...

Utilizing the Vuetify pagination feature in your project

I am in need of some guidance regarding the configuration of vuetify pagination. I have a card component that I loop through, but I also want to implement pagination around it. Any insights on where to start would be greatly appreciated? <v-pagination ...

The jQuery Validate Plugin only validates emails when the user moves away from the input field

Resolved: Upon inspecting my version of jquery-validate.js, I discovered that it was missing the onkeyup handler. Despite using version 1.12 Opre, which should have had this functionality according to its Github history from 2013, it seemed like there may ...

The revised document now exceeds 16,777,216 in size

When attempting to add new data to an array using mongoose, I encountered two errors. Here is the code snippet in question: return await db.fileMeta.findOneAndUpdate({ username: username, 'files.fileUID': { $ne: data.fileUID } ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

Importing three.js using ES6 syntax

When it comes to working with ES6, my workflow involves using Babel and babel-plugin-transform-es2015-modules-system.js specifically to transform module import/export for compatibility with system.js. I rely on a "green" browser for most ES6 features excep ...

What is the best way to customize the source code within node modules dependencies?

Hello everyone! I'm facing a challenge with my project. I'm trying to make changes to the code of a component from a UI library, such as Semantic-UI or Material-UI. Currently, I am directly editing the code within the node_modules folder. However ...

Can a custom function be executed using setTimeout in Node.js?

I am currently facing an issue with stopping the execution of my code for 2 seconds so that all ongoing animations can finish. I am attempting to implement a delay using setTimeout in Node.js. Here is what I have tried: this.userActivity = function(a,b, ...

Is it possible to modify the font color of a specific MenuItem in material-ui?

I've scoured every corner of the internet, but I'm still stumped by this question: How can I tweak the text color (not the background) for a selected or hovered MenuItem? I know the solution lies within useStyles, but my attempts thus far have be ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...