Categories
Automated Testing JavaScript Selenium

Selenium & JavaScript

Selenium documentation

Initialize the project

npm init -y
// https://www.npmjs.com/package/selenium-webdriver?activeTab=readme
npm i selenium-webdriver

Create a new test folder called tests and a new file called firstTest.js. Open the file and copy this code:

const { Builder, Browser, By, Key, until } = require('selenium-webdriver')

;(async function example() {
  //let driver = await new Builder().forBrowser(Browser.FIREFOX).build()
  let driver = await new Builder().forBrowser(Browser.CHROME).build()
  try {
    await driver.get('https://www.google.com/ncr')
    await driver.findElement(By.name('q')).sendKeys('webdriver', Key.RETURN)
    await driver.wait(until.titleIs('webdriver - Google Search'), 1000)
  } finally {
    await driver.quit()
  }
})()

Run the first test

node .\tests\firstTest.js
driver.executeScript("document.querySelector('tagname[attribute=value]').scrollIntoView()");
// Implicit waits
await driver.manage().setTimeouts({ implicit: 2000 });

// Explicit waits
let wrapper= await driver.findElement(By.className("wrapper"));
await driver.wait(until.elementIsVisible(wrapper), 2000);
// Right click
let wrapper= await driver.findElement(By.className("wrapper"));
await driver.actions().contextClick(wrapper).perform();
// Double click 
await driver.actions().doubleClick(wrapper).perform();
// Click
await driver.actions().click(wrapper).perform();
or 
wrapper.click();
// Type
await driver.actions().sendKeys(input,"Hello, world!").perform();
or
input.sendKeys("Hello, world!")