Testing in NestJs — Unit & E2E

Tushar Roy Chowdhury
2 min readMar 23, 2023

Hello there !!! It is irrefutable that testing is the most important part of software development. Apart from other testing strategies, unit tests as well as end-to-end tests are top of that list. In that case, we will be going to learn those strategies by testing an application that is developed in NestJs & MongoDB. So let’s jump in.

N.B. In case if you want to check out the full application. Here is the GitHub Link -Food-App-NestJS

In this dummy Food application, I am using MongoDB & mongoose schema to store my data. To perform the unit & e2e testing, we should use mocking data to test the code base. To follow up the mocking strategy I am using this package to mock my data —

"devDependencies":{
"@faker-js/faker": "^7.6.0"
}

In my dummy app, I have a module named restaurant. In the restaurant module, I am using a service for the restaurant to interact with MongoDB. So this is the restaurant.service.ts file-

Let’s write test for this- restaurant.service.spec.ts

Here, I have created some mocking service files & the Model documents to mock the DB calls. And also created a mocking file to get the necessary data as a replacement for the DB. To generate those fake data I am using @faker-js/faker. The line no 120–133, I am using the nesting query calls because if you look at the service file you will see the query. And Here is the fake.service.ts file -

And run this command to see the expected outcomes.

npm run test yourFlolderPath/Yourfile.service.spec.ts

So this way you can create your mock. With the help of this Mocking class, we can also use it for the restaurant.controller.spec.ts file too.

Execute the same command as you have seen above and should get the results. Now let’s move to the E2E testing which is basically the API testing. I normally do create the e2e test file in the root test folder. Here the e2e test file restaurant.e2e-spec.ts-

As you can see, I imported some fake JWT strategy that is mocking the actual one. And by using the JWT token I am executing the authorized API calls. In these API calls some guards have been implemented too. To run the test —

npm run test:e2e yourFolderPath/yourFile.spec-e2e.ts

I know these codes look irrelevant to you but you can have the whole project to use for learning purposes. Here is the GitHub Link -

FOOD APPLICATION USING NESTJS

Thanks a lot to read this far.

--

--

Tushar Roy Chowdhury

I am a passionate programmer and always keep eye on new technologies and scrutinize them until getting into shape.