Unit testing, Jasmine, PhantomJS
Date 07/10/2014
Unit testing in general
Unit testing, as the name suggests, is a way of testing units or portions of code.
Popular unit testing frameworks
PhantomJS, a headless WebKit browser
In an environment where there is no availability of screens, such as a server, continuous integration server specifically, is a need for tools which do not require the screen. One such tool specifically made for browser based testing, is PhantomJS.
However the latest release of PhantomJS, v1.9.8 from October 2014, is based on a WebKit from 2011. The next major release (v2.0.0) should be out soon and it will be based on a much newer WebKit, via Qt v5.3 which is used underneath.
Tasks for the day
Add unit tests to your
hello-node-jsrepository by usingnodeunitUnit test spec files are placed in a directory called
testsEach unit test file named as its targeting source file and
_spec.jssuffix
Add a task runner task for running the unit tests
Make sure that tests can be run after a fresh clone of the repository,
followed by
npm iand[task runner] test, for examplegrunt test
Links related to the lecture subject
Examples for the tasks
1. Unit tests with nodeunit
Install dependencies first:
npm i nodeunit --save-devCreate directory for tests and initial empty test file:
mkdir tests
touch tests/last-mod_spec.jsThe test can be written as the following JavaScript, assuming that the LICENSE file exists in the repository and its modification date is in October 2014.
// last-mod_spec.js
var lastMod = require('../last-mod');
exports.lastMod = function(test){
test.expect(4);
// Non existing file
var non = lastMod('not-to-be-found.js');
test.strictEqual(non, false, 'False returned when file not existing');
// Existing file
var yes = lastMod('LICENSE'); // Date object
test.equal(yes instanceof Date, true, 'Date object returned when file exists');
// Correct year and month
test.equal(yes.getFullYear(), 2014, 'Year is matching');
test.equal(yes.getMonth(), 9, 'Month is October');
test.done();
};Run the tests with:
node_modules/.bin/nodeunit last-mod_spec.js --reporter verbose2. Task runner for the unit tests
npm i grunt-contrib-nodeunit --save-devLast updated
Was this helpful?