Write a Unit Test With Mocha in Nodejs

There are many libraries available to write a unit test in nodejs like mochajs , jest i will show you how you can use mochajs to write unite test

first install dependency using npm

npm install mocha

Now suppose you have created a one function in repository like findUserByEmail() and if you have to check whether this function is working properly or not without attaching it to the routes and controller

Create a separate directory called test inside test directory you can create a subdirectory if have multiple service test cases, but for now i will create a single file in test directory and add that unit test inside that file

so directory structure will be like below

- test
    - users.repository.test.js

just suppose for if we pass email id then findUserByEmail function will return the data of that email, so i am not going to write a logic for this function.

content of our test file will be like below


var assert = require('assert');

describe("findUserByEmail", function () {
     it("findUserByEmail", async function () {
         var user = await findUserByEmail("email_id");

now add the mocha command line inside scripts key of package.json file like below

 "scripts": {
    "test": "mocha --recursive"

now for running the test case just simply run the npm test command and it will run all the test cases inside of test folder

if you want to run the specific test like if you want to run only single test case use the below command

npx mocha --recursive -g findUserByEmail

this command will run only findUserByEmail test function

comments powered by Disqus