Testing with Jasmine-Node
This week I have started testing my own code with Jasmine-Node. Testing seems beneficial only when we do it with a right approach. I have gone through various articles and find out Jasmine as one of the best frameworks for testing Javascript applications.
For specifically NodeJS, a better option will be to use Jasmine-Node.
How to start with Jasmine-Node ?
For a quick-start, you need to have Jasmine-Node installed with npm.
npm install jasmine-node -g
After the installation, make a folder say spec/ in the root directory of the project. This will contain all the tests for the node app.
We can include the command to run the tests in package.json file of the project.
./node_modules/.bin/jasmine-node spec
Like here it is included with the key tester. Now, we are ready to write our first test file.
So, in the Open-event-webapp spec/ folder I have created a file serverSpec.js. The file will test a basic function written in fold.js which is the file that includes all the functions of Open-event-webapp.
//fold.js 'use strict'; var exports = module.exports = {}; const fs = require('fs-extra'); const moment = require('moment'); const handlebars = require('handlebars'); const async = require('async'); const archiver = require('archiver'); //function to test function speakerNameWithOrg(speaker) { return speaker.organisation ? `${speaker.name} (${speaker.organisation})` : speaker.name; }
To test the above function, I have written the test like this
//serverSpec.js 'use strict' const request = require("request"); const fold = require(__dirname +'/../src/generator/backend/fold.js'); const port = process.env.PORT || 5000; const base_url = "http://localhost:"+ port +"/" describe("Open Event Server", function() { describe("GET /", function() { it("returns status code 200", function(done) { request.get(base_url, function(error, response, body) { expect(response.statusCode).toBe(200); done(); }); }); }); }); describe("Testing Fold.js",function() { describe("Testing SpeakerWithOrg function",function(){ it("it will test speakername", function(){ let speaker= { name: "speakername", } expect(fold.speakerNameWithOrg(speaker)).toEqual("speakername"); }); it("it will test speakername and organisation", function(){ let speakerWithOrg= { name:"speakername", organisation:"Organisation", } expect(fold.speakerNameWithOrg(speakerWithOrg)).toEqual("speakername (Organisation)"); }); }); });
There are two describe blocks here one to test if the server is running properly and the second block includes two ‘it’ statements which are used to test the function behavior.
The describe blocks are nested which is a nice feature provided by Node-Jasmine.
To run the above test in Open-event-webapp , use the command:
1. npm run start 2. npm run tester
On success, The output will be something like this
Other Sources
You must be logged in to post a comment.