Node.js Unit Testing

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

By Chintan Gor Node.js 2 days ago 12 min read 32 Views

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.

1. What Is Node.js Unit Testing?

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.

2. Overview Of Jasmine Framework

Jasmin testing framework is a Behaviour 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.

3. Various Test Cases Of Jasmine

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’.

4. Setting Up Jasmine Testing Framework

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

1. Download and install required Jasmine modules

2. Initialize the runtime environment

3. Inspect Jasmine configuration file

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

Installing the NPM Modules

The user must perform following steps:

1. Open the Node app

2. 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:

1. Open Node app

2. 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’.

5. 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:

1. Define code to test

2. Create and save file as ‘‘Add.js’’

3. 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.

4. Define Jasmine Node.js test code to test the “Add” function in saved Add.js file.

5. Create and save a file called “add-spec-js.

6. 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.

7. Run command jasmine.

Following screen appears.

C:\Users\Administrator\Projects\Sample>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.

6. 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:

1. Download and install npm

2. In the command line, run npm init option

Empty package.json file is created

3. 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:

1. Install an npm package

2. 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.

3. Install the request npm package with command: npm install request –save.

4. 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.

5. 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.

6. 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 –

1. 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.

2. 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.

3. Describe behaviour with command:

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

describe("GET /", function() {

});

});

4. In Jasmine it block, write first expectation:

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

describe("GET /", function() {

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

});

});

});

5. In the request package, send the GET request towards the server

6. In Node.js, load the package with the keyword required

7. 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) {

});

});

});

});

8. 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:

1. In the app directory, save a file as “hello_world.js” with the following command : touch app/hello_world.js.

2. In the Express package, route and answer incoming HTTP requests with the command : var express = require(‘express’);.

3. In Express, create an empty application with the following : var app = express();.

4. In Express’s routing mechanism, set up the routes:

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

res.send("Hello World");

});

5. 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);

6. 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:

1. 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");

});

});

});

2. 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.

3. 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();

});

});

});

});

4. 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 App Development Company who is dealing with Jasmine Framework.

FAQ

There are 3 major things that you need to follow for utilizing Jasmine:

Firstly installing Jasmine framework using NPM
Second is preparing the test code using ‘spec’
Third running the code using jasmine command

Jasmine is an open-source testing framework for JavaScript. It helps you to test the app in an efficient way. With Jasmine, there is no need for IDE.

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

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.

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

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.

There are a lot of testing frameworks that can be utilized for Node.js. But, the most popular ones are Jasmine, Karma, Jest, and AVA.

Node.js Unit Testing

Disclaimer: We at eSparkBiz Technologies have created this blog with all the consideration and utmost care. We always strive for excellence in each of our blog posts and for that purpose, we ensure that all the information written in the blog is complete, correct, comprehensible, accurate and up-to-date. However, we can’t always guarantee that the information written in the blog correct, accurate or up-to-date. Therefore, we always advise our valuable readers not to take any kind of decisions based on the information as well as the views shared by our authors. The readers should always conduct an in-depth research before making the final decision. In addition to these, all the logos, 3rd part trademarks and screenshots of websites & mobile apps are the property of the individual owners. We’re not associated with any of them.

Chintan Gor

Chintan Gor

Enthusiastic for web app development, Chintan Gor has zeal in experimenting with his knowledge of Node.js 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 blogs on Node.js. He is associated with eSparkBiz – a Node.js Development Company from the past 7-8 years where one can get premium services.

Search

Follow us

Subscribe Newsletter

Call us Today

telephone

Got any Questions?
call us Today!

+1 408 850 1488 [email protected]

Our Guides

Related Post

Top 40 Node.js Packages For Increasing Developer Productivity

Top 40 Node.js Packages For Increasing Developer Productivity

Node.js is a platform created on Chrome's JavaScript runtime. It is used to create quick and scalable network applications. Node.js Packages helps you to employs…

10 Shares
Node.js vs Java: The Ultimate Battle For Being Best Back-End

Node.js vs Java: The Ultimate Battle For Being Best Back-End

The discovery of new tools and technologies in the digital age pushes humans further towards automation and makes our lives easier. Developers working on technologies…

5 Shares
Node.js vs ASP.NET : Which Is One Is Best For Enterprise App Development?

Node.js vs ASP.NET : Which Is One Is Best For Enterprise App Development?

Web development is taking new twists and turns every year with new trends, frameworks, languages, tools, etc. being released into the development field. Today we’re…

7 Shares
Share via
Copy link