a blog for those who code

Tuesday 25 October 2016

Getting Started With Test Driven Development in Nodejs

In this post we will be discussing about test driven development in Node.js. Testing is an important practice in software development to improve software quality, improve your workflow and allow you to develop scalable applications. There are many types of testing involved like manual testing, integration testing, functional testing, load testing, unit testing and other.

Introduction of Test Driven Development


According to Wikipedia, Test-driven development is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only. This is opposed to software development that allows software to be added that is not proven to meet requirements.

In simple terms using testing driven development we are going to write a test before starting any new feature or program specification of our application. So whenever we start coding for our application we are going to start with the code that tests what my program is supposed to do. So until our code gives the required output the test which we have written will fail. Once our test is passed it is sure that our feature is behaving correctly and then we can go ahead with the next test and feature and repeat the process for the whole application.

Four rules of TDD

1. Write a test for the specific feature
2. Run the test and watch it fails
3. Implement the feature
4. Run the test and watch it pass

Test Driven Approach in Node.js using mocha


Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.


Installation

You can install mocha using npm command as shown below :

npm install mocha --g

To get started with Mocha you need to create a test folder inside your application folder and then we wll create a test.js file inside it. One more thing to note that mocha allows you to use any assetion librray like should.js, expect.js or chai.

Lets take an example of a TodoApp where our first feature would be adding a new Todo. So for this feature of adding a new todo, the possible test cases would be that the database count of todos should increase by 1.

describe('dataTest', function() {
  it('todo count should increase by 1', function () {
    var todos = data.todos.get();
    data.todos.save({todoName : 'Write Coding Defined 1st Post'});
    var latestTodos = data.todos.get();
    latestTodos.length.should.equal(todos.length + 1);
  });
});

In the above test we have used describe function which is used to set up a group of test with a name. A test is written using the it function which is given a description as the first argument of what the module under test should do and the second argument will contain one or more assertions using should.js. Now when we run out test by calling mocha it will give the below output.


Our test is failing which is correct because we haven't implemented the functionality. Our next step is to create the getting and saving functionality and see if our test is passing. One thing to note that we are getting the reference error as well, so first we have to get away with the reference error, for that we have created one more file named data.js and modified our test.js file as below :

Contents of test.js

var should = require('should');

describe('dataTest', function() {
  var data = require('../data.js');
  it('todo count should increase by 1', function () {
    var todos = data.todos.get();
    data.todos.save({todoName : 'Write Coding Defined 1st Post'});
    var latestTodos = data.todos.get();
    latestTodos.length.should.equal(todos.length + 1);
  });
});

Contents of data.js

module.exports = {
  todos : {
    get: function() {
      return [];
    },
    save: function() {
    }
  }
}

After running mocha again you will see something like below which is telling us that expected value does not match.


Our next step is to make our test pass for that we will change our data.js file as shown below where we have created a todos.json file in our application.

var fs = require('fs');
module.exports = {
  todos : {
    get: function() {
      var data = fs.readFileSync('./todos.json', 'utf-8');
      return JSON.parse(data);
    },
    save: function(todo) {
      var data = fs.readFileSync('./todos.json', 'utf-8');
      var todos = JSON.parse(data);
      todos.push(todo);

      fs.writeFileSync('./todos.json', JSON.stringify(todos));
    }
  }
}

Now when you run mocha you will see something like below which means your test passed


Conclusion


In this post we have looked at a practical example of unit testing in Node using Mocha testing framework and using should as assert. Although you may say that Test-driven development approach adding additional complexity to the development process, it helps us build a stable application with fewer errors.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment