Search code examples
javascriptselenium-webdrivercucumberpom.xml

Not getting the last list element text value when implementing POM in Cucumber Selenium JS


I'm trying to use POM model where I put all my web elements in a seperate page. What I did is create a new function and call it in my step_definition folder.

I'm writing a script that if I enter a to-do list item, it should be added last to the current list of items. However, it always gets the 2nd to the last item if I use as xpath: //li[last()]

Here's the script in the step_definition folder:

When('User adds a task', async function () {
    loginPage.enter_toDo("Learn Selenium")
});

Then('task is added', async function () {
    let toDoText = await loginPage.getLastItem().getText().then(function(value) {
        return value
    })
    assert.equal(toDoText, "Learn Selenium");

Here are the functions in the page_object folder:

class LoginPage extends BasePage {
    async enter_toDo(toDoText) {
        await driver.findElement(By.id("sampletodotext")).sendKeys('Learn Selenium',Key.RETURN);
    }

    getLastItem () {
        return driver.findElement(By.xpath("//li[last()]"))
    }

}

I'm expecting to get "Learn Selenium" but I always end up with the 2nd to the last item. I tried replacing loginPage.enter_toDo("Learn Selenium") with await driver.findElement(By.id("sampletodotext")).sendKeys('Learn Selenium',Key.RETURN); in the step_definition and it works, but this defeat the purpose of POM.


Solution

  • You missed await in loginPage.enter_toDo.

    I guess, when you trying to sendKeys into input, last li element is appeared.

    enter_toDo function is async, so when you calling it in When block without awaiting for Promise to be resolved, Then is executed while Promise of loginPage.enter_toDo is in Pending state.

    Modify your code as follows:

    When('User adds a task', async function () {
        await loginPage.enter_toDo("Learn Selenium")
    });