How I Setup Unit Test for MongoDB using Jest & Mongoose
Background
I am working on a backend microservices project which adopted tech stack like MongoDB, Express Framework, RabbitMQ and etc. And recently, I am assigned to develop a pretty big feature which involving changes and the logic flow across different microservices. I drafted down the flow in the screenshot below.

It’s pretty challenging and time-consuming if you want to set up and run all the relevant projects and performs the end-to-end testing since the bug could have occurred everywhere within all these different microservices when your scope is huge.
Solution Design
The solution that came to my mind is unit testing the code in each microservice.
Unit Testing is important when you’re working on microservices project. This is because you would want to ensure your code is working properly before you did the integration test. The integration test could be difficult and complicated depending on your business use case.
This is the first time where I feel like writing a unit test is way easier. However, we will focus on MongoDB Unit testing only in this article.
Implementation
Without further ado, let’s draft out and breakdown the implementation step.
- Basic Express App Setup
- Create a User Model using Mongoose
- Setup Jest & MongoDB Memory Server
- Unit Testing
Basic Express App Setup
The app is running using Express framework. The expected outcome of this setup is we will have a functioning application which connected to our MongoDB.
The following dependencies are required in order to complete the setup.
- dotenv. This is the popular library used to manage our environment variable. The common use case is you would store your MongoDB connection string here, so you can easily configure your connection string for a different environment.
- Mongoose. Data Modeling library for MongoDB.
Why Mongoose?
The reason why I use Mongoose instead of MongoDB Node Driver is because of Schema and Validation. I would not go deep into Mongoose. Basically what Mongoose provided is allow me to intentionally define the field that I want and whether the field is mandatory or optional. Coding intentionally is very important and it’s our responsibility to know each line of code serving what purpose.
Seems complicated? Don’t worry about the setup. I got you covered by setting you up the required dependencies. You can download or clone the code via Github and set up your own unit test project seamlessly.
Create User Model using Mongoose
After we have successfully set up the project. Before we create the model, we must know what we want.
Which means what are we expecting from the User model. Let’s say we would want to know user’s name, date of birth, age and login using what kind of social account. This process is known as definingschema
in Mongoose.
Defining the schema is easier than you think. Here are the steps and the code:
- Define UserSchema.
- Create UserModel with the defined UserSchema.