Testing NodeJS app using Mocha and Chai
Introduction:
Once you are done with coding the main features of your app, it is very important to implement standard software testing methodologies. In order to make sure that your app behaves as expected, you have to write code coverage test cases.
Software testing is very useful when you are introducing new modules in your app. Having a testing environment with test cases already in place, makes it very easy to check quickly if this new module is introducing new bugs in the app.
In this tutorial, we will learn how to write unit test cases using Mocha and Chai in a NodeJS application. Just to give a basic introduction of other these libraries, Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser. Chai is an assertion library for node.
In this tutorial, I will show a Simple ToDo list endpoints along with User authentication endpoints and then show how test cases are written for code coverage.
ToDo APIs:
First, we need to create ToDo model. Here is the document structure for the same:
Here are the basic end points for reading and writing entries in ToDo list :
Below shown code is another route to retrieve a todo list item given its id.
User APIs:
Here is the structure for User Model.
Here are the basic end points for user signup and login :
Test Cases:
In order to do test coverage, we add dummy data both User and ToDo Collections.
Here are few tests written for ToDo routes:
The below shown route will add new items to the ToDo list and test it.
Here are few tests for User Route :
This test demonstrates how we can test the user login route.
This below shown code tests the user signup route.
Conclusion:
You can access the complete code on this Github link. I hope this tutorial helps you get a good understanding of how you can write test cases for your application in NodeJS.