Jasmine + PhantomJS
In this tutorial, we will be using PhantomJS, a headless scripted browser built on WebKit, to launch tests with the grunt-contrib-jasmine test-runner.
We first install PhantomJS.
npm install phantomjs
Next, we install grunt-contrib-jasmine
plugin locally to run Jasmine specs through PhantomJS
npm install grunt-contrib-jasmine --save-dev
Consider a JavaScript file test.js
, containing two functions, pi()
and sin()
. The function pi()
returns the value of π
(upto 3 decimal places) and the function sin()
returns a numeric value between -1 and 1, for a given argument in radians
function pi() {
return 3.141;
}
function sin(x) {
return Math.sin(x);
}
This file is saved inside the src
directory.
We write the specs in Jasmine (below) to check that the value of π returned by pi()
equals 3.141
and the value of the trigonometric ratio sine is always ≤ 1 and ≥ -1, for any random number generated between 1 and 100. We name this spec file test.spec.js
and save it inside the spec
directory
describe("Value of pi", function() {
it("is equal to 3.141", function() {
expect(pi()).toEqual(3.141);
});
});
describe("Value of sine", function() {
it("is less than or equal to 1", function() {
expect(sin(Math.floor((Math.random() * 100) + 1))
<= 1).toBeTruthy();
});
it("is greater than or equal to -1", function() {
expect(sin(Math.floor((Math.random() * 100) + 1))
< -1).toBeFalsy();
});
});
And finally, Gruntfile.js
is created and configured as shown below
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
test: {
src:'src/test.js',
options: {
'specs': 'spec/test.spec.js'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('default', ['jasmine']);
}
Jasmine specs can now be run typing either the command
grunt jasmine
or
grunt