Skip to content

Instantly share code, notes, and snippets.

@sauceaaron
Last active June 11, 2019 15:28
Show Gist options
  • Save sauceaaron/064f98c0dcf9ca77b8edd15bf19fc9d8 to your computer and use it in GitHub Desktop.
Save sauceaaron/064f98c0dcf9ca77b8edd15bf19fc9d8 to your computer and use it in GitHub Desktop.

To execute this code you need to have Node.js installed. It can be obtained at https://nodejs.org

Install the selenium-webdriver package:

npm install -g selenium-webdriver

I used the static-server package to host the sample login page:

npm install -g static-server

static-server -i login.html

To run the sample code:

node login.js

<html>
<head>
<title> Login Page </title>
</head>
<body>
<h1> Login </h1>
<form id="login">
Username: <input id="username"/>
Password: <input type="password" id="password"/>
<button type="submit"> Login </button>
</form>
</body>
</html>
// use selenium and launch browser
var selenium = require('selenium-webdriver');
var browser = new selenium.Builder().forBrowser('chrome').build();
// map of page element locators
var loginPage = {
username: selenium.By.id("username"),
password: selenium.By.css("form#login > input#password"),
loginButton: selenium.By.xpath("//button[@type='submit']")
}
// interact with locators
browser.get("http://localhost:9080");
browser.findElement(loginPage.username).sendKeys("Aaron");
// add functions to interact with page elements
loginPage.getUsername = function() {
return browser.findElement(this.username);
}
loginPage.setUsername = function(username) {
var element = this.getUsername();
element.clear();
element.sendKeys(username);
}
loginPage.setPassword = function(password) {
browser.findElement(this.password).sendKeys(password);
}
loginPage.getLoginButton = function() {
return browser.findElement(this.loginButton);
}
// login function
loginPage.login = function(username, password) {
this.setUsername(username);
this.setPassword(password);
this.getLoginButton().click();
}
// site object
class MySite {
login(username, password) {
browser.get(mysite.url);
loginPage.login(username, password);
}
}
mysite = new MySite();
mysite.url = "http://localhost:9080";
mysite.login("aaron", "secret");
browser.quit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment