Codementor Events

Testing NodeJS app using Mocha and Chai

Published Aug 25, 2019
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:
todoModel.png

Here are the basic end points for reading and writing entries in ToDo list :
todo API -1.png

Below shown code is another route to retrieve a todo list item given its id.
todo API -2.png

User APIs:

Here is the structure for User Model.
userModel.png

Here are the basic end points for user signup and login :
User APIs.png

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:

test-ToDo-1.png

test-ToDo-2.png

The below shown route will add new items to the ToDo list and test it.
test-ToDo-3.png

Here are few tests for User Route :
This test demonstrates how we can test the user login route.
test-User-1.png

This below shown code tests the user signup route.
test-User-2.png

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.

Discover and read more posts from Ashish
get started
post commentsBe the first to share your opinion
Show more replies