Unit Testing for Nest.js Applications with Vitest

Updated on:
03.10.2024
4.8
939
5 min

Testing is an essential phase for any application, especially for server-side apps, where outcomes are harder to verify visually compared to client-side apps. We need to be confident that our server application is performing its intended functions correctly. One of the most common and efficient ways to achieve this confidence is through unit testing.

Working on a server application powered by Nest.js, we encountered a specific challenge. The default testing library recommended by Nest.js documentation is Jest, which works well for basic scenarios. But while Jest performs adequately in simple cases, our application was handling long-running external API requests and complex calculations. We started noticing memory issues when running tests with Jest. Since we had frequently used the Vitest library for client-side apps, we decided to try it for our Nest.js app as well.

What is unit testing?

Unit testing allows you to verify separate parts of your code, like functions, methods, or classes. In our case, the app needed to expose a REST API, and in the controllers, we used standard Nest.js services, such as this one:

Our task in hand was to test these services through unit testing. First, we needed to integrate Vitest with our application. Here’s how we set it up:

Installing Vitest in Nest.js

We installed the following dependencies:

Next, we created a configuration file for Vitest:

Running tests

We added two tasks to package.json for running tests:

  • The test task is used for running tests quickly, especially in repository pipelines. 
  • The test:coverage task takes more time as it evaluates code coverage and updates the README.md file with the coverage badges. We use this task when adding, removing, or editing tests.

Example: Testing the list method in ProductService

Here’s an example of how we tested the list method in our demo ProductService.

In this example, the beforeEach section is necessary to create a testing module and retrieve the required ProductService from it. The subsequent it sections are responsible for directly testing the service methods. You can learn more about how Vitest works at Vitest API.

We created numerous tests and checked complex modules, and we didn’t encounter any memory issues. The task was successfully completed, and Vitest played a crucial role in making this possible.

Bottom line

The project in hand was quite unique in its properties and execution, which called for a tailored approach. As a team of designers, developers, and engineers specializing in custom coding, it was an excellent case for us to come up with specific solutions and apply uncommon techniques based on the very particular vision of the client. 

How do you rate this article?
4.8
Voted: 6
We use cookies to improve your experience on our website. You can find out more in our policy.