Automated Browser Testing With Nightwatch & Cucumber

What Is Nightwatch?

Nightwatch is a thin JavaScript API overlaying the Selenium WebDriver API. This allows us to control the Selenium browser automation from JavaScript code in a manner most familiar to JavaScript and UI developers.

What is Cucumber?

Cucumber is library for implementing Behavior Driven Development. IT codifies a simple format (Gherkin) for writing specifications for a system which should be readable by both technical contributors and non-technical users/stakeholders alike.

Why Would I Use Them Together?

When you combine Nightwatch and Cucumber, writing test scenarios becomes relatively painless, and attaching logic to those scenarios is very easy. The real value comes from the fact that when paired, you get exceptional reporting on those test scenarios. You can even include screenshots of the automated browser in your reports!

Setting It All Up

Install Dependencies

  1. Install Nightwatch

    yarn add --dev nightwatch nightwatch-api
  2. Install CucumberJS

    yarn add --dev cucumber-js
  3. Install Cucumber Reporting Libraries

    yarn add --dev cucumber-pretty cucumber-html-reporter

Create Configuration

  1. Create the nightwatch configuration

    1. From the command-line, run nightwatch to cause it to generate an initial configuration file

    2. Modify the nightwatch.conf.js file as follows:

  2. Create the cucumber configuration file <root>/cucumber.conf.js

  3. Add script entries to package.json for running the Cucumber tests

  4. Create the directory <root>/features/step-definitions

Create Your First Specification

  1. Create your first .feature file as <root>/features/Login.feature with the following contents

  2. Define steps to satisfy your feature steps in the file <root>/features/step-definitions/steps.js

Run Your First Scenario

  1. Run the tests and produce a report using npm run test:cucumber.

    1. Once the tests complete, your browser should open to show an HTML report like this:

Implement Your Own Scenario

  1. Edit the <root>/features/Login.feature file and create a new scenario called ‘Prevent login submission when invalid e-mail is present’

    1. Example:

    2. IF your IDE supports Cucumber/Gherkin, you might see the steps which do not have definitions yet highlighted. like this:

       

    3. In IntelliJ/WebStorm, you should be given the option to implement those steps.

    4. Otherwise, add new steps to <root>/features/step-definitions/steps.js for the 2 new steps

  2. Implement steps in <root>/features/step-definitions/steps.js

  3. Run both scenarios with npm run test:cucumber and you should see a report like the following:

     

Â