我使用 Java、Selenium 和 Chrome 进行自动化测试。我们的开发人员最近将我们的 UI 从 AngularJS 升级到 Angular2(不确定这是否重要)。但从那时起,sendKeys 就在文本字段中输入不完整的字符。这是一个例子:
public void enterCustomerDetails()
{
txtFirstName.sendKeys("Joh201605130947AM");
txtSurname.sendKeys("Doe201605130947AM");
txtEmail.sendKeys("[email protected] /cdn-cgi/l/email-protection");
}
我也尝试过使用executeScript。它不起作用。它可以输入完整的字符,但表单认为该字段为空。
public void forceSendKeys(WebElement element, String text)
{
if (element != null)
((JavascriptExecutor) this.webDriver).executeScript("arguments[0].value=arguments[1]", element, text);
}
public void enterCustomerDetails()
{
forceSendKeys(txtFirstName, "Joh201605130947AM");
forceSendKeys(txtSurname, "Doe201605130947AM");
forceSendKeys(txtEmail, "[email protected] /cdn-cgi/l/email-protection");
}
我还尝试在 .sendKeys 之前使用 .click() 并添加睡眠时间。他们也没有工作。
我从这篇文章中得到了一个逐一输入字符的想法:如何在 selenium webdriver 的文本字段中一一输入字符? https://stackoverflow.com/questions/24492795/how-to-enter-characters-one-by-one-in-to-a-text-field-in-selenium-webdriver/24522875
它有效,但这意味着我必须将所有代码从 sendKeys 重写为新函数:
public void sendChar(WebElement element, String value)
{
element.clear();
for (int i = 0; i < value.length(); i++){
char c = value.charAt(i);
String s = new StringBuilder().append(c).toString();
element.sendKeys(s);
}
}
public void enterCustomerDetails()
{
sendChar(txtFirstName, "Joh201605130947AM");
sendChar(txtSurname, "Doe201605130947AM");
sendChar(txtEmail, "[email protected] /cdn-cgi/l/email-protection");
}
如果大家知道更好的方法,请帮忙! :)