Server side testing with Mocha for Node.js

This article is a continuation of our previous articles about http://www.docomomoiberico.com/?dissertation-defense-presentation-economics Single Page Application with Angular.js, Node.js and MongoDB part 1 and http://constructionandlandscape.com/?p=academic-essay-writing-service-uk part 2.

In general, we appreciate unit testing in application, because at the time of delivery, we have much confidence about our piece of software regarding non-breaking of the code-base in production. There are integration tests, regression tests in our application, but we do not include those part in current scope of article, rather we emphasis on unit testing from development perspective.

We tried to cover the tests of methods of server side here. We expect, reader is already have some knowledge about unit testing of components in any given application. A test driven environment always help us through development life cycle for better maintainability of code-base and less iteration on bug fixing.

Our challenges are to

1> create most of the code-base testable so that unit testing can be done.

This point can be achieved using proper javascript design patterns.

2> test the asynchronous methods of node.js

Here mocha comes in play.

So codes and explanations are given below in-line for the given application, which can be downloaded from essaywriter github.

To make out code more testable, we had separated the Rest api layer and DAO Layer. Even we can break the code further with service layer for complex code-base, what we had not done here for our project simplicity.

Testing explanations of Data Access methods –

We had taken one variable for our dao class –

http://majestichha.com/?q=writting-essay-for-pay var userwork = require(‘../dataaccess/userdao’);

Below are two testing methods and explanations for dao layer methods –

 
describe('sampleapps', function(){
  describe('mongogetmethod', function(){  click here // A name for the test
    it('the method should return value as string', function(done){  follow link // expectation from the method
	userwork.getUser(function (err, userString) {  http://1limoblack.com/?p=how-to-write-creative-brief // Calling of the method
		var jsonVar = JSON.parse(userString); 
		var convertVar = JSON.parse(jsonVar);
		expect(convertVar.length).to.be.above(0);  here // Testing results with expect
		done();	 online games essay // test framework method to indicate end of testing
	});
    })
  });
});

Now another one for insert user in mongodb –

 
describe('sampleapps', function(){ 
  before(function(){  source // Startup event where we should create environment for the test
    	userwork.removeUser('piyas.de@gmail.com', function (err) {
		 view // Just removed this user if exists, to ensure that the test method works.
	});
  })
  describe('mongoinsertmethod', function(){
    it('the method should add document to collection', function(done){  http://q8sec.com/?p=college-essay-help // Expectation from the method
	userwork.insertUser(
          '{"username":"Piyas De","password":"1234","email":"piyas.de@gmail.com"}', function (err) { 
               http://emarketalliance.com/?p=help-me-write-my-dissertation // Insert the user
		userwork.getSingleUser('piyas.de@gmail.com',function (err, userString) {
                         http://bluntmax.com/homework-help-kent/ // test whether the user inserted or not
                        // through calling the user information from mongodb
			var jsonVar = JSON.parse(userString);
			var convertVar = JSON.parse(jsonVar);
			expect(convertVar.length).to.be(1);
			done();  buy essay paper online // test framework method to indicate end of testing
			  // done() is used to test the asynchronous methods in node.js, the
                        // Testing framework understand the end of the test
		});
	});

    })
  })
  after(function(){ // Event, where cleanup code can be written to remove any object, which
                    // is/are created during testing  
    	userwork.removeUser('piyas.de@gmail.com', function (err) {
		// Just removed this user if exists
	});
  })
}); 

Also reader can learn about testing of other db methods by reading the code.

Testing explanations of Rest API methods –

We have explained test methods for both the REST Apis which are given below –

 

describe('sampleapps', function(){
  describe('getusers', function(){ // The method name
    it('should return a collection greater than 0', function(done){ // expectation of the method
        // The server should run before testing
    	request.get('http://localhost:8080/getusers').end(function(res){ // The rest call through request
       		expect(res).to.exist; // Response exists
		expect(res.status).to.equal(200);
		var jsonVar = JSON.parse(res.text);
		expect(jsonVar.length).to.be.above(0); // Expect the number of users greater than 0
                // we have not created any start up method to insert user as we knew of user existence.
                // Start-up method to be written to insert user to ensure success of the test
		done(); // indicate end of test
  	});
    })
  });
});

// User Insert Rest APi Testing
describe('sampleapps', function(){
  describe('post method', function(){
    it('should insert a record in database', function(done){// expectation of the method
    	request.post('http://localhost:8080/insertuser') // A post request
               .send(
               'mydata={"username":"Ketaki Nandi","password":"1234","email":"ketakinandi@gmail.com"}')
               .end(function(res){
		userwork.getSingleUser('ketakinandi@gmail.com',function (err, userString) {
	       		var jsonVar = JSON.parse(userString);
			var convertVar = JSON.parse(jsonVar);
			expect(convertVar.length).to.be(1);
			done(); // indicate end of test
		});
  	});
    })
  })
  after(function(){  // Cleanup method of the Test
    	userwork.removeUser('ketakinandi@gmail.com', function (err) {
		// Just removed this user if exists
	});
  })
});

A little note –

Reader should study mocha from the site to learn the commands to execute the test.

We will explain Client side tests for angular.js methods in next article.

Reader can download the complete source-code in GitHub.

Also if you find this article helpful, you can connect us in Google+ and Twitter.

Leave a Reply

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