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.
This article was originally published in 2016. It looks like Nightmare is no longer actively maintained.