Using Nightwatch with the selenium-webdriver library Suggest edits

The selenium-webdriver NPM library is the official Node.js binding from the Selenium project. Starting with v1.5, you can use it for scenarios where you need to extend the built-in commands or features of Nightwatch.

It is also possible to run tests exported from the Selenium IDE, with a bit of configuration changes. You can combine Nightwatch assertions with elements retrieved using the selenium-webdriver APIs.

Here's how to do it:

  1. record your test using the Selenium IDE (with the provided Chrome or Firefox extensions);
  2. export the recorded test using the JavaScript Mocha export option; you do not need to change the Nightwatch runner, the default one also will work;
  3. change the config as needed – at the very least you need to disable the Nightwatch session – see below for an example;
  4. run the test using the nightwatch test runner

Full API documentation is available at the Selenium API docs page.

Example

The test below was recorded and exported using the Selenium IDE Firefox extension and modified with a few Nightwatch assertions being added.

// Generated by Selenium IDE
const { Builder, By, Key, until } = require('selenium-webdriver')
const assert = require('assert')

 describe('Selenium IDE Test', function() {
   this.timeout(30000)

   // The session is no longer managed by Nightwatch, but the geckodriver still is
   this.settings.start_session = false;

   let driver
   let vars

   beforeEach(async () => {
     const builder = new Builder()
       .forBrowser('firefox')
       .usingServer(this.settings.webdriver.url); // use the geckodriver started by Nightwatch

     driver = await builder.build();
   })

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

   it('navigate to url', async function(nightwatch) {
     await driver.get("https://nightwatchjs.org/")
   })

   it('sampleTest', async function(nightwatch) {
     await driver.manage().window().setRect(1383, 1175)

     const element = await driver.findElement(By.linkText("Getting Started"));

     // By default, elements retrieved using the Selenium APIs have no selector property;
     // this is only used for output in Nightwatch assertions
     element.selector = 'By.linkText("Getting Started")';

     // The Nightwatch expect/assert APIs are now accepting elements retrieved using the Selenium APIs
await nightwatch.expect.element(element).visible; await nightwatch.assert.visible(element); // You can also use third-party assertion libraries; here the built-in assert library is used const textResult = await element.getText(); assert.strictEqual(textResult, 'Getting Started'); // Now the two options of clicking an element are equivalent
await element.click(); //await nightwatch.click(element); // 4 | click | linkText=Home | | // await driver.findElement(By.linkText("Home")).click() }) })
Improve this article