avatarTek Loon

Summary

The web content provides a guide on setting up unit tests for MongoDB using Jest and Mongoose in a backend microservices project.

Abstract

The article details the author's experience with implementing unit tests for MongoDB within a microservices architecture. The author emphasizes the importance of unit testing in such projects to ensure code reliability before moving on to integration testing. The guide covers the initial setup of an Express app, creating a User Model with Mongoose, and configuring Jest alongside MongoDB Memory Server to facilitate in-memory testing without affecting the actual database. The author provides step-by-step instructions, code snippets, and test cases to demonstrate the process, aiming to simplify the setup for developers and encourage the practice of unit testing by removing common obstacles.

Opinions

  • The author believes that unit testing is crucial in microservices projects to ensure that each service works correctly before integration testing.
  • The author expresses that setting up unit tests for MongoDB can be challenging but is made easier with the right tools and configurations.
  • Jest is praised for its preset configurations for MongoDB, which simplify the setup process for unit testing.
  • The use of MongoDB Memory Server is advocated to prevent test data from being stored in the production database.
  • The author suggests that the effort and time spent on dependencies mocking and configuration can be a demotivating factor for developers, but the right setup can alleviate this.
  • The article concludes by asserting that with proper tooling, unit testing can be an impressively straightforward task that builds trust within a development team.

How I Setup Unit Test for MongoDB using Jest & Mongoose

Photo by Joshua Aragon on Unsplash

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.

Microservices Flow and Forgive my handwriting

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.

  1. Basic Express App Setup
  2. Create a User Model using Mongoose
  3. Setup Jest & MongoDB Memory Server
  4. 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:

  1. Define UserSchema.
  2. Create UserModel with the defined UserSchema.

Now we have a working schema and model. Let’s proceed to set up Jest and the unit testing.

Setup Jest & MongoDB Memory Server

Step-by-step guide Firstly we have to install Jest. I choose to install it as a dev dependency so that everyone who checkout this project can use it without installing any dependency globally in their own workstation.

npm install jest --save-dev

I would say Jest is a perfect match with MongoDB when coming to unit testing as Jest comes with the preset with MongoDB which provided all the configuration and only minimal setup is required. I will explain more in a short while. For now, let install the preset.

npm install @shelf/jest-mongodb --save-dev

Then, create jest.config.js within your project directory.

After that, create jest-mongodb-config.js within your project directory with the following content.

That’s all for the configuration. Easy, right?

Why Jest Preset with MongoDB? This preset assists you to configure all the settings MongoDB Memory Server.

Why we need MongoDB Memory Server? This is because when you run your unit test, you wouldn’t want your unit test dummy date to be saved into your real database. Thus, MongoDB memory server provides you the ability to store your data in memory only.

With this preset, we can ignore most of the setup that demotivates us from and spends most of our time on the real stuff which is writing the unit test.

Unit Testing

Now we know the Why and How part. Let’s do some unit test on the UserModel we just created. Let’s configure our mongoose connection to Mongo Memory Server and I also listed down some very simple example test cases.

Here’s the list of test cases that we’re going to test against.

  • Insert User into Database successfully. (Test Normal Use Case)
  • Insert User with Invalid Field. (Test on Schema)
  • Insert User without Required Field. (Test on Validation)

You can also refer to the gist below.

Conclusion

In my opinion, developers are always motivated and keen on doing unit testing. But however, the dependencies mocking and configuration which takes effort and time is always an obstacle and demotivation factor.

I experienced that myself which I have no clue on how to resolve the dependencies in order to continue the writing of unit test. Lastly, I skipped the unit testing and that was a bad feeling.

Now with all the preset and configuration is ready for you with simple setup, you can write the unit test with minimal effort. Trust me, your unit test will impress your teammates.

The expressway to build trust with your programmer’s teammates: Write Tests.

Lastly, I hope that this article does inspire you to write your unit test and also giving you information writing unit test could be easier than you imagined.

References

Thanks for reading.

JavaScript
Programming
Jest
Mongodb
Web Development
Recommended from ReadMedium