Skip to content

Instantly share code, notes, and snippets.

@taiiiraaa
Last active August 1, 2020 19:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taiiiraaa/21cea94eca7632001750ae88180da265 to your computer and use it in GitHub Desktop.
Save taiiiraaa/21cea94eca7632001750ae88180da265 to your computer and use it in GitHub Desktop.
Automated browser testing with Nightmare, Mocha and Chai

Nightmare is a browser automation library for Node.js. It can be used with Mocha and Chai to create BDD style tests.

Before we start, check to make sure Node.js is installed on your system.

Use npm to install all the required packages. If package.json doesn't exist, run npm init first.

npm install mocha --save-dev
npm install chai --save-dev
npm install mocha-generators --save-dev
npm install nightmare --save-dev

Now let's write some tests in the BDD style.

require('mocha-generators').install();
var Nightmare = require('nightmare');
var expect = require('chai').expect;

// Mocha
describe('Login to site', function(){

    var nightmare;

    // It runs before each test
    beforeEach(function*() {

      nightmare = Nightmare();

      // Login to the site first
      yield nightmare
          .goto('https://example.project/login')
          .type('form#login-form input[name="username"]', 'test123')
          .type('form#login-form input[name="password"]', 'testpass')
          .click('form#login-form input[type="submit"]');
    });

    it('Should see a title "Welcome back"', function(done){
        nightmare
            .goto('https://example.project/')
            .evaluate(function(){
                return document.querySelector('h1').textContent;
            })
            .end()
            .then(function(title){
                // Chai
                expect(title).to.equal('Welcome back')
                done();
            });
    });

    // It runs after each test
    afterEach(function*() {
        // End the Nightmare instance
        yield nightmare.end();
    });
});

The script will login to a site and then test the title is a particular string. Based on the Stackoverflow answer.

Run the test with Mocha

#For globally installed Mocha
mocha tests/
# For locally installed Mocha
./node_modules/mocha/bin/mocha tests/ --reporter nyan

--reporter nyan is optional.

One of the interesting feature of Nightmare is:

// open browser window
nightmare = Nightmare({show:true});

Which will open a browser window and you will be able to see all the page interactions. Behind the scenes Nightmare uses Electron, a Node.js desktop app framework which provides a wide range of API to interact with the Chromium browser.

@taiiiraaa
Copy link
Author

This article was originally published in 2016. It looks like Nightmare is no longer actively maintained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment