Mocha and Chai Unit Testing

I have been learning about JavaScript unit testing frameworks lately and found them to be quite neat while implementing!
Mocha and Chai are one of them.
Why do we need them?
That is a good question! They help in developing maintainable and clean code.
The approach to be followed is to find the smallest available piece and just test it.
Mocha is a mechanism that runs the test and Chai is just an assertion library.

I have written unit tests to check the presence of admin or not.
This is my controller which implements a function to pass roles -- user and admin.

Here are the unit tests for the above function.
In my first function, 'isAuthorized', since two different parameters are supplied, the test will return false.


Similarly, in the second test, the array contains admin, and hence it will return true, as specified by the the assert function.

The following is the result :


It shows the passing and failing tests!

This makes it much easier to test functions and build better code.

Download/Clone my source code from GitHub to practice more :

I would really like to thanks, Stephen MacNeil, PhD Candidate from University of North Carolina at Charlotte to introducing me to this! He is a great teacher plus a friend and I definitely learned a lot and have been using all my learnings in my projects in every possible way.

Mocha and Chai Unit Testing
Share this

Subscribe to Rujuta Mahindrakar