Before we can run any tests, we must tell Selenium which browser to use. Chrome is, by far, the most popular browser in use today, and so we will start with using ChromeDriver. Let's install it:
$ yarn add chromedriver --dev
Now, inside spec/cucumber/steps/index.js, define Before and After hooks which are run before each scenario:
import { After, Before } from 'cucumber';
import webdriver from 'selenium-webdriver';
Before(function () {
this.driver = new webdriver.Builder()
.forBrowser("chrome")
.build();
return this.driver;
});
After(function () {
this.driver.quit();
});
In the Before hook, we are creating a new instance of the driver. A driver is akin to an user session, and a session can have many windows opened (just like you can have multiple tabs opened at the same time).
The webdriver.Builder constructor function returns with an instance that implements the ThenableWebDriver interface, which allows us to specify parameters for the driver by chaining methods together. Some popular methods include the following:
- forBrowser: Specify which browser to use.
- withCapabilities: Passes parameters to the browser command. Later on, we will use this to run Chrome in Headless Mode.
Once the parameters have been set, terminate the chain using the build method to return an instance of the driver.
In the After hook, we are disposing the driver using the quit method. This will close all windows and end the session.
We are storing the driver instance in Cucumber's World (the context) for other steps to use.