skip to Main Content

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.

2

Answers


  1. Update your getLastItem method in the Page Object to use WebDriverWait.

    const { By, Key, until } = require('selenium-webdriver');
    
    class LoginPage extends BasePage {
        async enter_toDo(toDoText) {
            await driver.findElement(By.id("sampletodotext")).sendKeys(toDoText, Key.RETURN);
        }
    
        async getLastItem() {
            const lastItem = await driver.wait(until.elementLocated(By.xpath("//li[last()]")), 5000); // Adjust the timeout as needed
            return lastItem;
        }
    }
    
    

    Modify the step definitions to await the getLastItem method will solve this.

    When('User adds a task', async function () {
        await loginPage.enter_toDo("Learn Selenium");
    });
    
    Then('task is added', async function () {
        let toDoText = await loginPage.getLastItem().getText();
        assert.equal(toDoText, "Learn Selenium");
    });
    
    Login or Signup to reply.
  2. 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")
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search