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 –

require(‘should’);

Some of the testing which are one-liner –

Boolean variable functionality testing –

 
true.should.be.ok;

false.should.not.be.ok;

true.should.be.true;

'1'.should.not.be.true;

false.should.be.false;

''.should.not.be.false;

Checking array functionalities –

 

[].should.be.empty; // 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

[].should.be.an.instanceOf(Array); // Instance of an array

Checking of some string functionalities –

 

''.should.be.empty; // 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 –

 

(4).should.equal(4);

(10).should.be.above(5);

(15).should.be.within(10, 15);

(10).should.not.be.below(5);

Undefined and Infinity checking –

 

(undefined + 0).should.be.NaN;

(1/0).should.be.Infinity;

javascriptnosqlbook

JSON functionalities checking –

 

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

({}).should.be.an.Object; // An Object

var jsonVar = {a:1, b:2}; 

jsonVar.should.have.property('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 –

 

(function(){
  throw new Error('fail');
}).should.throw();

var user = {
    name: 'tj'
};

user.should.have.property('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 *