Basic API operations with Express JS and Unit Testing with mocha

Krishnendu Halder
6 min readMay 3, 2020

--

Image source is google image and edited with MS Power Point

Introduction

Almost every developer who worked with Node.js should know about Express.js. It is one of the popular node.js based framework which is being used by so many developers now a days in entire world.

Unit Testing is one of the major steps in Software Development cycle, where developers should have the knowledge of writing some good and reliable unit testing scripts to validate the functionalities of each units (i.e. small part of code or single components) of the application or API and gain the confidence. To meet this requirement another popular node.js based unit testing framework is mocha.

Here in this article we will demonstrate, how we can develop our own API in our local system with some basic operations with Express JS and then we will write a Unit Testing script with the help of mocha to validate it’s functionalities.

So with that set let’s begin!

Source Code

Project Flow and Description

Here we will develop a dummy API to provide information related some book to the end users which will contain the topic of the book , it’s author, description and ID. The schema of the API fields mentioned below.

{“id”: number,
“topic”: String,
“description”: String,
“author”: String}

Once the API is developed we will perform GET, POST and DELETE operations on it and validate the results with Unit Test scripts.

Project Dependencies

To install the dependencies please run a command call npm install from the command prompt.

Initialize Express First

In the project folder you will find one javascript file called ‘app.js’, which is the main file in this entire project. This file is responsible to initialize express and run it on localhost:3000 . Please refer the below snapshot and output for more clarity.

Code snippet to initialize express js

To check whether the express is up and running or not, run command node <file name> and check the console, if the provided log displaying on the console then express is successfully running a server on localhost:3000. Refer the below snapshot of the output.

Console log

Create a dummy Data base

Once express is up and running then we will create one dummy database file named as ‘post_db.js’ which is placed under ‘db’ folder of the project. The reason of this file is to store some predefined data as object and later we will access it through API call. Please refer below code snippet for reference.

Create GET call

So now we have some dummy data with us which we can get in read only form by using a GET call through API. So let’s quickly write some code to create a GET with the help of Express JS

Code snippet of GET call
  1. The ‘get’ is express property which represents the GET call of the API.

2. under the ‘get’ we are assigning the status code of the call as 200 which we can get from the server if the call is successful.

3. ‘Send’ is used to send back a response from the server once the API call is successful.

4. The ‘/api/v1/allposts’ is the endpoint of the GET API call. The base URI (Uniform Resource Identifier) of the API starts with ‘http://localhost:3000’ as it will run on localhost 3000 port only.

So now if we perform the GET call through postman we will get the response like below.

GET request on Postman

Create a new record using POST call

As we know POST call helps to create or insert some new value or record to the data base through API. Here also we will do something similar.

  1. Here ‘/api/v1/create/post’ is endpoint for POST call, and the base URI is same as previous.
  2. Within the ‘post’ we are checking few of the field’s value which are mandatory to create a new record through API. Status code 400 has been assigned in case some mismatch found with the body (the payload which needs to be provided for POST), and along with that it will send back some meaning full and understandable messages as well to the end users.
  3. Status code 201 will be generated if the POST call is succeed.

Let’s perform a POST call through Postman and see the output.

Body for POST request
201 status code once POST call is succeed

Now again perform GET call to see whether newly added record is created or not.

GET call. Previously it was 2 records now it is 3 after POST call

Delete an existing record with DELETE

Let’s see how we can perform the DELETE operation through our API. We will try to delete an existing record by it’s id.

DELETE call through API
  1. ‘/api/v1/posts/:id’ is the DELETE endpoint. ‘:id’ means end user has to provide the respective id to delete some record.
  2. Status code will be 200 for successful Delete operation.
  3. If ‘id’ will not exists anymore in the existing record then API will display message as ‘No posts found to delete’.
Deleted record ID=3

Let’s validate the result through GET call

Record ID=3 is deleted now

Let’s try delete an invalid id

As record 3 is already deleted hence giving error response with 404 status code

Please refer the entire code snippet below.

Unit Testing

Now the time is to validate the entire flow whatever we have done so far through some automated test script and here it is.

This Unit Testing script is available within a folder called ‘test’ under the root directory of the project folder, and to run this file write command npm test on console. As mocha has incorporated as dev dependency in this project and test path is provided under package.json file hence it can be executed through the mentioned command.

Once the test execution will complete, mocha will provide you an understandable report or status on the console like below.

Unit Test status generated by mocha on console

Conclusion

So as we know the importance of Express JS in current technical era where node.js is doing such a great job in software development field, hence thought to share my own understanding through this article. This article can be helpful to those who wants to start exploring express js from very basic level, just like me :) . I hope you will get some relevant information on Unit Testing as well.

References

https://medium.com/@purposenigeria/build-a-restful-api-with-node-js-and-express-js-d7e59c7a3dfb

https://medium.com/@osahonoboite/testing-restful-apis-using-mocha-chai-and-chai-http-plugin-4b9feb45d50

https://expressjs.com/en/starter/installing.html

https://mochajs.org/

Something about MySelf :)

Hello, my name is Krishnendu Halder, I am a 26 years old Senior Software Engineer, staying in Bangalore, India. My specialty is on Software QA domain mainly but I am very much interested about learning technologies and development. You can reach me on LinkdIn. Please hit on the clap icon in case you feel it helpful for you. Thank You again.

--

--

Krishnendu Halder

Software Engineer who is interested about design, architecture, testing and deployment. A passionate larner and collaborator.