In-Depth Guide On Node.js Unit Testing With Jasmine Framework

Reading Time: 8 minutes

Quick Summary :- This guide on NodeJS unit testing with Jasmine framework introduces what Node.js unit testing is with a small overview of Jasmine framework. Thereafter various test cases of Jasmine have been discussed with steps to set up a jasmine testing framework with detailed codes. The guide ends with a FAQ section to clear more air on the topic.

eSparkbiz Technologies Pvt Ltd
Chintan Gor (CTO, eSparkBiz)

Testing is a critical aspect of any software development project. This is because its omission will have a detrimental impact on user experience. To release a bug-free product, JavaScript testing is the ideal solution. Today we will talk about Node.js Unit Testing with Jasmine Framework.

JavaScript testing not only helps finding bugs in the early stage of development, but also assists in releasing stable software to its users. Features of Node.js also contribute to this aspect with the in-built capability of unit testing. Let’s analyze how this whole process works.

What Is Node.js Unit Testing & Overview Of Jasmine Framework

The framework deployed in Node.js unit testing was formerly called JsUnit in the early 2000s. Over time, this framework had a number of upgrades and now it has become Jasmine.

The Jasmine framework enables automated Node.js unit testing – an essential practice to develop modern web and mobile-based apps. That’s why companies need to hire Node.js developer so that they will utilize this practice.

Jasmin testing framework is a Behavior Driven Development (BDD) testing framework. So, there is no requirement of a JavaScript framework.

Therefore, Jasmine is highly suitable for the Node.js unit testing framework, websites, or other places where JavaScript based frameworks function effectively.

This is such a crucial aspect when you’re dealing with Node JS Unit Testing. It will help you to deal with the testing scenario in a better manner.

Various Test Cases Of Jasmine Framework

The different test case of the Jasmine Testing Framework:

Suites

As a call to global function ‘describe’, it considers the argument as function and String. The String provides a suite title while the global function is a code block for the implementation purpose.

Specs

It is a call to the global Jasmine testing function that also takes the form of a String and a function. String is the spec title, with the function a test.

A spec comprises expectations examining the state of code that you need test. Furthermore, there can be several ‘it’ functions in a describe block.

Expectation

In a Jasmine testing framework, the expectation is an assertion that can either be true or false. There can be many assertions in one spec.

One can generate Expectations with an ‘expect’ function, taking the argument as the actual value. The argument is then clubbed with a Matcher function, i.e. the expected value.

Matchers

Each Matcher test case implements a Boolean comparison between the expected and actual value with Matchers deployed to compare both.

If all Matchers are true, the test is passed. If not, it is deemed as a failure. Some Matcher functions consist of ‘toBeTruthy’ and ‘toBe’.

Setting Up Jasmine Testing Framework

To setup the Jasmine testing framework, user performs the following steps:

  • Download and install required Jasmine modules
  • Initialize the runtime environment
  • Inspect Jasmine configuration file

The user must then perform additional steps to complete setting up Jasmine Testing framework.

Installing the NPM Modules

Installing the NPM Modules

The user must perform following steps:

  • Open the Node app
  • Install the Jasmine framework module with the following command: npm install jasmine-node

Initializing Project

The Jasmine test framework creates a configuration json and spec directory for users with the latter storing all test files, enabling the Jasmine framework to execute them.

The json file stores particular config data about the Jasmine testing framework.

The user must perform the following steps:

  • Open Node app
  • Run command: jasmine init.

Inspecting Configuration File

The configuration file is usually under the name jasmine.json in the spec/support folder. The file enumerates both the spec and source files that the user needs Jasmine node framework to include. A coding snippet explains this.

{

“spec_dir”: “spec” // Shows Successful Execution

“spec_files: [

“**/*[sS/] pec.js” // Shows Successful Execution

],

“helpers”: [

“helpers/**/*.js”

],

“stopSpecOnExpectationFailure”: false,

“random”: false

Note – Spec directory has been specified in this example. When the Jasmine testing framework is executed, it searches for every directory test. Another important aspect is spec_files parameter. Any created test files must be appended with keyword ‘spec’.

How to Conduct Node.js Unit Testing with Jasmine?

To use Jasmine test framework properly and to conduct Node JS Unit Testing, refer to the next example. Initially, a module is defined, following which, two numbers are added.

A separate code file comprising test code is then added with the Jasmine test framework deployed to test the ‘Add’ function as needed.

User performs following steps:

  • Define code to test
  • Create and save file as ‘‘Add.js’’
  • In file “Add.js”, enter the code
var exports=module.exports={};

exports.AddNumber=function(a,b)

{

return a+b;

};

Note – The keyword ‘exports’ guarantees that defined functionality is accessible by other files. A function ‘AddNumber’ takes two parameters, a and b, and adds them to the ‘exports’ module ensuring public accessibility. Lastly, function returns the added value of the two parameters.

  • Define Jasmine Node.js test code to test the “Add” function in saved Add.js file.
  • Create and save a file called “add-spec-js.
  • In file“add-spec-js”, enter code
var app=require("../Add.js");

describe("Addition",function(){

it("The function should add 2 numbers",function() {

var value=app.AddNumber(5,6);

expect(value).toBe(11);

});

});

Note – Add.js file is included to test  ‘AddNumber’ function in file. In the Node.js testing framework module that is created, the first part describes a name (‘’Addition”).

A description with ‘it’ method is next. Addnumber is then invoked along with sending parameters 5 & 6, passed onto the AddNumber method. Lastly, a comparison of the actual test is done.

  • Run command jasmine.

Following screen appears.

C:UsersAdministratorProjectsSample>jasmine

Started

.

.

.

1 spec, 0 failure

Note– Any Errors are displayed on the screen.

Summary

To test Node.js unit test framework, Jasmine must be installed along with Node package manager. Test code is written separately, with ‘spec’ appended to the file name.

Without this, the Jasmine test framework is unable to detect files. Lastly, the test is run by executing Jasmine testing framework command, finding all files with word ‘spec’ attached.

Testing Node.js Server with Jasmine Testing Framework

Bootstrap the Server

To setup and download dependencies, users use Node.js Unit Testing Framework from the official package manager (npm).

The major advantage of npm is that it initializes an empty project directory with the option of init command.

User performs following steps:

  • Download and install npm
  • In the command line, run npm init option
    Empty package.json file is created
  • In package.json file, answer the on-screen questions as below:
{

"name": "Hello World",

"version": "0.0.1",

"description": "Simple Hello World demo app.",

"main": "index.js",

"scripts": {

"test": "echo "Error: no test specified" && exit 1"

},

"author": "",

"license": "ISC"

}

A directory for Jasmine Unit Testing along with the server source code is set up. Usually, tests written in the Jasmine testing framework module are known as specs and saved in the directory.

mkdir app

mkdir spec

At this stage, the project tree must have the below pattern:

├── app

├── node_modules

├── package.json

└── spec

Installing Dependencies

To write specs in Jasmine test framework, user perform the following steps:

  • Install an npm package
  • In the project root directory, run command: npm install jasmine-node –save.
    The ‘save’ option automatically appends the package to the file and saves the package version.
  • Install the request npm package with command: npm install request –save.
  • Install Express.js with command: npm install express –save.
    Note – The Express.js package defines simple Domain Specific Language for the purpose of routing and handling HTTP requests.
  • Setup npm’s test command to run Jasmine specs with command: ./node_packages/.bin/jasmine-node spec.
    Note – Jasmine node is installed locally in node_packages directory within project root directory.
  • In package.json file, enter command from the previous step.

Following file appears

{

"name": "Hello World",

"version": "0.0.1",

"description": "Simple Hello World demo app.",

"main": "index.js",

"scripts": {

"test": "./node_modules/.bin/jasmine-node spec"

},

"author": "",

"license": "ISC"

}

Understanding the Hello World Server

The following steps are performed –

  • In the new spec/hello_world_spec.js file, type the following: touch spec/helloWorldSpec.js.
    Note – Jasmine framework specs explain units of code or one feature. Thus, specs begin with describing blocks comprising tests linked to those features.
  • Describe the file with the command:
describe("Hello World Server", function() {

});

Note – First argument provides a brief description of the tested feature, while second executes expectations.

The user must ensure that the server returns to HTTP status OK (status code 200) when a GET request is sent to the root path.

  • Describe behavior with command:
describe("Hello World Server", function() {

describe("GET /", function() {

});

});
  • In Jasmine it block, write first expectation:
describe("Hello World Server", function() {

describe("GET /", function() {

it("returns status code 200", function() {

});

});

});
  • In the request package, send the GET request towards the server
  • In Node.js, load the package with the keyword required
  • To execute a request, pass request function and URL
    Note – After the request returns, there is an invoking of both URL and function.
var request = require("request");

var base_url = "http://localhost:3000/"

describe("Hello World Server", function() {

describe("GET /", function() {

it("returns status code 200", function() {

request.get(base_url, function(error, response, body) {

});

});

});

});
  • Write first expectation:
var request = require("request");

var base_url = "http://localhost:3000/"

describe("Hello World Server", function() {

describe("GET /", function() {

it("returns status code 200", function() {

request.get(base_url, function(error, response, body) {

expect(response.statusCode).toBe(200);

});

});

});

});

Note – The procedure is nearly complete, but there is a chance that the it block may finish before the expectation, as the Node.js testing framework is an asynchronous environment.

To avoid this, the done callback function – a callback only in Jasmine-node is used to synchronize expect with it:

var request = require("request");

var base_url = "http://localhost:3000/"

describe("Hello World 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();

});

});

});

});

Note – You should call the demo function should only if the expectation is executed. If there is no call to done() or reason (code error or similar), Jasmine terminates this ‘it’ block and considers it as a failed example.

Implementing Hello World Server

The user performs following steps:

  • In the app directory, save a file as “hello_world.js” with the following command : touch app/hello_world.js.
  • In the Express package, route and answer incoming HTTP requests with the command : var express = require(‘express’);.
  • In Express, create an empty application with the following : var app = express();.
  • In Express’s routing mechanism, set up the routes:
app.get("/", function(req, res) {

res.send("Hello World");

});
  • To make the app listen to an incoming request on a port, write the command : app.listen(3000);.

Note – At this point, the user should ensure that the app looks like this :

var express = require('express');

var app     = express();

app.get("/", function(req, res) {

res.send("Hello World");

});

app.listen(3000);
  • Run the Jasmine test again with the command: npm test.

NoteThis is to check if the spec description and implementation align with each other.

The following output appears.

> [email protected] test /home/igor/hello_world

> jasmine-node spec

..

Finished in 0.007 seconds

2 tests, 0 assertions, 0 failures, 0 skipped

Read also: Exploring The Best Node.js Application Examples For Big Enterprise

The Hello World Generator

Through a Hello World Generator, a user can request the required number of Hello Worlds with the server returning them as JSON arrays.

To do so, the user can create a function that considers a number as the parameter to return an array with those many ‘Hello World’ strings in them.

The user performs the following steps:

  • In the Jasmine Test framework, write the specs with the command:
touch spec/generatorSpec.js

var generator = require("../app/generator");

describe("Hello World Generator", function() {

it("returns an array", function() {

expect(generator.generateHelloWorlds(0)).toBe([]);

});

it("returns the correct number of Hello Worlds", function() {

var result = generator.generateHelloWorlds(3);

expect(result.length).toBe(3);

});

it("returns only Hello Worlds", function() {

var result = generator.generateHelloWorlds(3);

result.forEach(function(element) {

expect(element).toBe("Hello World");

});

});

});
  • To populate an Array, write a simple for loop with the command:
touch app/generator.js


exports.generateHelloWorld = function(number) {

var result = [];

for(var i=0; i < number; i++) {

result.push("Hello World");

}

return result;

}

Note – In this case, there is an implementation of function as part of the export’s namespace. This tells the node to make the function visible to other modules.

  • To check if the server accepts query parameters and returns the correct arrays, rewrite the spec/helloWorldSpec.js as:
var request = require("request");

describe("Hello World Server", function() {

describe("GET /", function() {

it("returns status code 200", function(done) {

request.get("http://localhost:3000", function(error, response, body) {

expect(response.statusCode).toBe(200);

done();

});

});

it("returns Hello World array", function(done) {

request.get("http://localhost:3000?number=3", function(error, response, body) {

expect(body).toBe(JSON.stringify(["Hello World", "Hello World", "Hello World"]));

done();

});

});

});

});
  • Rewrite the implementation of the Hello World server as:
var generator = require('./generator');

var express   = require('express');

var app = express();

app.get("/", function(req, res) {

var number = req.params.number;

var helloWorldArray = generator.generateHelloWorlds(number);

res.send(200, helloWorldArray);

});

app.listen(3000);

Conclusion

The JavaScript framework has certainly progressed by leaps and bounds since its inception more than two decades ago.

Writing web and mobile apps is now extremely simple and straightforward, and with the Jasmine Node JS, it would not be an exaggeration to even call testing a pleasurable experience.

We hope you had a great time reading this article and it proves to be of great value for any Node js Web Development Company who is dealing with Jasmine Framework.

Chintan Gor

CTO, eSparkBiz

Enthusiastic for web app development, Chintan Gor has zeal in experimenting with his knowledge of Node, Angular & React in various aspects of development. He keeps on updating his technical know-how thus pinning his name among the topmost CTO's in India. His contribution is penned down by him through various technical blogs on trending tech. He is associated with eSparkBiz from the past 14+ years where one can get premium services.
Frequently Asked Questions
  1. How do you run a jasmine test case?

    Steps to run jasmine test case:

    1. Install Node.js
    2. Install jasmine and run npm install -g jasmine.
    3. cd to any directory
    4. set up an example
    5. Now run your unit tests

  2. Is Jasmine a BDD or TDD?

    BDD means Behavior Driven Development and TDD means Test-Driven Development. Jasmine is A Behavior Driven Development (BDD) framework.

  3. What Is The Difference Between BDD & TDD?

    BDD means Behavior Driven Development. So, this approach focuses on checking the behavior of the system. While TDD means Test-Drive Development. So, this approach focuses on checking various functionalities.

  4. What Is Unit Testing?

    Unit Testing means you will test the individual unit or components of the system. A unit is the smallest part of any software.

  5. How To Check If Node.js is Working or Not?

    In Windows Command Prompt, Powershell, or any other command-line tool, you should type node -v & if that returns a version number, you’re set.

Expert Insights For Digital Product Development

We at eSparkBiz are passionate about discussing recent technologies and applications. We constantly write blogs and articles associated with the field of technology. So, don't miss our detailed and insightful write-ups. You'll find all our latest blogs and blog updates here.

Node.js Microservices: Build Scalable and Efficient Applications

eSparkbiz Technologies Pvt Ltd
Chintan Gor CTO, eSparkBiz

Once your applications begin to grow and surpass a certain threshold, it is time you settle on an architecture that will make adding new features…

Top Node.js Interview Questions to Ask Before Hiring a Node.js Developer

eSparkbiz Technologies Pvt Ltd
Chintan Gor CTO, eSparkBiz

NodeJS emerged recently in the tech landscape as an effective JavaScript framework to develop lightning-speed server apps. With companies racing to design robust digital product…

The Ultimate Guide to Node.js Development Services for Scalable Web Solutions

eSparkbiz Technologies Pvt Ltd
Chintan Gor CTO, eSparkBiz

NodeJS has been ranked as the number one framework leveraged by Node.JS developers around the globe. Nearly 40.8% of skilled developers worldwide make use of…