我正在尝试使用 POM 模型,将所有 Web 元素放在一个单独的页面中。我所做的是创建一个新函数并在我的 step_definition 文件夹中调用它。
我正在编写一个脚本,如果我输入待办事项列表项,则应将其添加到当前项目列表的最后。但是,如果我用作 xpath,它总是会获得倒数第二个项目:
//li[last()]
这是step_definition文件夹中的脚本:
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");
以下是page_object文件夹中的函数:
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()]"))
}
}
我期待得到“学习硒”,但我总是以倒数第二项结束。我尝试在step_definition中用
loginPage.enter_toDo("Learn Selenium")
替换await driver.findElement(By.id("sampletodotext")).sendKeys('Learn Selenium',Key.RETURN);
并且它有效,但这违背了POM的目的。
更新页面对象中的 getLastItem 方法以使用 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;
}
}
修改步骤定义以等待 getLastItem 方法将解决此问题。
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");
});