Skip to main content

_javascript

TL;DR - Show Me The Code

6-open-new-window/code/javascript/test/window.spec.js
const assert = require("assert");
const {Builder} = require("selenium-webdriver");

describe("New Window and New Tab", function () {
let driver;

beforeEach(async function () {
driver = await new Builder().forBrowser("firefox").build();
});

afterEach(async function () {
await driver.quit();
});

it("opens new window", async function () {
await driver.get("https://the-internet.herokuapp.com/windows");
await driver.switchTo().newWindow('window');
await driver.get("https://the-internet.herokuapp.com/typos");
const windowHandles = await driver.getAllWindowHandles();
assert(windowHandles.length === 2);
});

it("opens new tab", async function () {
await driver.get("https://the-internet.herokuapp.com/windows");
await driver.switchTo().newWindow('tab');
await driver.get("https://the-internet.herokuapp.com/typos");
const windowHandles = await driver.getAllWindowHandles();
assert(windowHandles.length === 2);
});
});

Code Walkthrough

Importing Libraries

First, we are pulling in our requisite classes our testing framework (e.g., mocha and require("assert")), and driving the browser with Selenium (e.g., const {Builder} = require("selenium-webdriver");).

Setup and Teardown

After creating a describe to group our tests (e.g., describe("New Window and New Tab")...), the following lines are setting up and tearing down the browser instance.

The beforeEach method, will execute before each test. In it, we are launching a new instance of Firefox with Selenium and storing it in a class variable that we'll use throughout all tests. After our test executes the second method, afterEach, will execute. This calls driver.quit() which ends the session by closing the browser instance.

Open New Window

opens new window shows how to open a new window, switch to it, and assert the number of window handles open. They key to this is the await driver.switchTo().newWindow('window') line. Which opens a new window and switches to it.

Open New Tab

opens new tab shows how to open a new tab, switch to it, and assert the number of window handles open. They key to this is the await driver.switchTo().newWindow('tab') line. Which opens a new tab and switches to it.

Executing the Test

Before executing the test, we need to make sure the required dependencies are declared on the package.json file.

Toggle to see the package.json file.
6-open-new-window/code/javascript/package.json
{
"dependencies": {
"selenium-webdriver": "4.24.0"
},
"description": "A project to showcase opening a new tab or window using the official WebdriverJs",
"devDependencies": {
"mocha": "10.7.3"
},
"license": "MIT",
"name": "open-new-window",
"scripts": {
"test": "npx mocha test/**/*.spec.js --timeout 60000"
},
"version": "1.0.0"
}

Finally, we can run the test by executing npm test from the command-line.