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
Update your getLastItem method in the Page Object to use WebDriverWait.
Modify the step definitions to await the getLastItem method will solve this.
You missed
await
inloginPage.enter_toDo
.I guess, when you trying to
sendKeys
into input, last li element is appeared.enter_toDo
function isasync
, so when you calling it inWhen
block without awaiting for Promise to be resolved,Then
is executed while Promise ofloginPage.enter_toDo
is in Pending state.Modify your code as follows: