DEV Community

Cover image for Unit testing in Nodejs Using Mocha
Bibek Dhami
Bibek Dhami

Posted on • Originally published at bvek.hashnode.dev

Unit testing in Nodejs Using Mocha

To do unit testing in node we will be using mocha for running test cases and chai for BBD styles test cases.

STEP 1: Install Dependency

npm install mocha
npm install chai
npm install chai-http
Enter fullscreen mode Exit fullscreen mode

STEP 2: Initialize test File

Getting Ready Test File
require chai, chai-http and require file which starts your server

setupTest.png
add mocha test in scripts in package.json to run test cases

script.png

Step 3: Writing Test

As to be able to run only one test case at a time we can create an object with a unique key and assigning values true and false and we can use those object values to allow the test case to run only when the respective object key value to true by checking with if condition.Note if condition by default check for true no need to specify like this (test case.addObject == true). We can define our test content type with .set to form-url encoded or application/JSON as required. Here Application/JSON will be used
Creating Object with unique key and value. As our code to be tested is an async function we need to set the parameter of it block function to done so that when mocha sees that our it block has a test case

creatingObject.png

test for add person
As the function we are testing is an async function we need to specify done in our test case

addPerson.png
Patch(Update) Person

patchPerson.png
for Get Person
getPerson.png

We can group the test case in a single function to make it more organize and distinguish from other unrelated test cases like this:

singleFunctionPerson.png
add Favourite and get Favourite

FavouriteAll.png

Step 4: *Running Test
*

Now run the test case

npm test
Enter fullscreen mode Exit fullscreen mode

SourceCode

Top comments (0)