The situation here is try to test login feature. When I tried to sendKeys to userId and password field(check the code below). Sometimes the keys for the password go to the username field.sometimes loginBtn finished executing and the userId and password fields haven't been inserted with keys.Below is my code:
var webdriver = require("selenium-webdriver");
var test = require("selenium-webdriver/testing");
var assert = require("assert");
var By = require("selenium-webdriver").By;
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
testAfterLogin();
function testAfterLogin() {
driver.get("https://xxxxx.com");
var userid = driver.findElement(By.id('xxxxyyy'));
userid.clear();
userid.sendKeys("userId");
var password = driver.findElement(By.id('yyyyzzzz'), 2000);
password.clear();
password.sendKeys("password");
var loginBtn = driver.findElement(By.className("btnBtn"));
loginBtn.click();
}
I think because of node js runs non-blocking, it is not always executed line by line. is there way to fix this problem? Thank you ahead! enter image description here
We can use webdriver.until.elementLocated(locator) to fix this problem. Below is the example code.
var userId = driver.wait(until.elementLocated(By.id('UserID')))
userId.sendKeys("test");
var pwd = driver.wait(until.elementLocated(By.id('Password')))
pwd.sendKeys("123456");
var loginBtn = driver.wait(until.elementLocated(By.className('btn-login')))
loginBtn.sendKeys(webdriver.Key.ENTER);