Node.js Unit Testing with Should.js

One of node.js unit testing javascript library is should.js.
After having node.js in machine, we have to install should.js through npm(node package manager).

To install should.js we need to run in terminal –

npm install should

To enable should.js in any given javascript file, we have to include –


Some of the testing which are one-liner –

Boolean variable functionality testing –;;;



Checking array functionalities –


[]; // Array is empty

[1,2,3].should.eql([1,2,3]); // Array contains same values as expected

[1, 2, 3].should.have.length(3); // Array length checking

[1,2,3].should.containEql(1); // The Array contains value as expected

[]; // Instance of an array

Checking of some string functionalities –


''; // Empty String

'foobar'.should.endWith('bar'); // String end with some expected string

'foobar'.should.not.endWith('foo'); // String should not end with some expected string

'test'.should.equal('test'); // String equality checking

Checking of some number functionalities –




(15), 15);


Undefined and Infinity checking –


(undefined + 0);



JSON functionalities checking –


({ foo: 'bar' }).should.eql({ foo: 'bar' }); // JSON Equality checking

({}); // An Object

var jsonVar = {a:1, b:2};'a'); // JSON Property Checking

var obj = { foo: 'bar', baz: 'raz' }; 

(obj).should.containEql({ foo: 'bar', baz: 'raz' }); // JSON contains the expected value

obj.should.have.keys('foo', 'baz'); // JSON has the keys

obj.should.have.keys(['foo', 'baz']);

Function should throw the error –


  throw new Error('fail');

var user = {
    name: 'tj'
};'name', 'tj');

To test functionalities independently with ‘Describe’, we have to intstall automatic test runner. Here mocha is a automatic test runner and it will run the tests and show the results in console.

Now we need to install mocha –

npm install -g mocha

Now the function for Testing –


function sumTwoNumbers(firstNum,secondNum)
	return (parseInt(firstNum) + parseInt(secondNum));

To test this function, we need to run –
mocha shouldexplore.js which is the name for the test case file.
If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner

2 thoughts on “Node.js Unit Testing with Should.js

Leave a Reply

Your email address will not be published. Required fields are marked *