Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automated browser testing with Nightmare, Mocha and Chai

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

Check to make sure Node.js installed. Update to the latest LTS version if you can node -v.

Use npm to install the dependencies and add it to package.json. 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.

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