Login a form
Setup nodeJs project
$ mkdir nodejs-project
$ cd nodejs-project
$ npm init
$ yarn add selenium-webdriver chromedriver
Code template – Login a form
const assert = require('assert');
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
require('chromedriver');
// Init web driver
const driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
// Main process
(async () => {
// Open a website
await driver.get('http://localhost:8000/index.html');
/////////////////////////////////////
// Do something here
// Wait until username input is visible
await driver.wait(until.elementLocated(By.id("login-username")));
await driver.findElement(By.id('login-username')).sendKeys('username');
await driver.findElement(By.id('login-password')).sendKeys('password');
// Wait until login button is visible
// await driver.wait(until.elementLocated(By.id("login-button")));
// await driver.findElement(By.id('login-button')).click()
// If button is unclickable you can try this way
const elLoginBtn = await driver.findElement(By.id('login-button'));
var times = 0;
while (times < 100)
{
try {
times++;
await elLoginBtn.click();
break; // Clickable
} catch(error) {}
}
})();
How to check if form is logged in successfully?
(async () => {
...
/////////////////////////////////////
// Do something here
driver.findElement(By.xpath('//*[@id="home"]/div[2]/div/table/tbody/tr[2]/td[1]/a')).getText().then(function (value) {
assert.equal(value.trim(), "My Profile");
});
})();
Reference
Set up a testops using selenium webdriver
Leave a Reply