API with NestJS #8. Writing unit tests

JavaScript NestJS TypeScript

This entry is part 8 of 168 in the API with NestJS

Testing our application can increase our confidence when it comes to creating a fully-functional API. In this article, we look into how we can test our application by writing unit tests. We do so by using some of the utilities built into NestJS, as well as the Jest library.

If you would like to get to know Jest better first, check out the first part of the JavaScript testing tutorial.

Testing NestJS with unit tests

The job of a unit test is to verify an individual piece of code. A tested unit can be a module, a class, or a function. Each of our tests should be isolated and independent of each other. By writing unit tests, we can make sure that individual parts of our application work as expected.

Let’s write some tests for the  .

src/authentication/tests/authentication.service.spec.ts

PASS src/authentication/tests/authentication.service.spec.ts
The AuthenticationService
when creating a cookie
✓ should return a string (12ms)

When we execute  , Jest looks for files ending with   and executes them.

We can improve the above code. Each of our tests needs to be independent, and we need to ensure that. If we add more tests in the above file, all of them will use the same instance of the  . It breaks the rule of all tests being independent.

To deal with it, we can use the   that runs before every test.

src/authentication/tests/authentication.service.spec.ts

Now, we are sure that every test in the   file gets a brand new instance of the  .

Unfortunately, the above code does not look very elegant. Because the constructor of the   expects some dependencies, we provided them manually so far.

Creating testing modules

Fortunately, NestJS provides us with built-in utilities to deal with the above issue.

By using   we can create a module with its dependencies resolved.

src/authentication/tests/authentication.service.spec.ts

There are quite a few issues with the above code still. Let’s deal with them one by one.

Mocking the database connection

The biggest issue above is that we use the   which means connecting to the real database. When doing unit tests, we want to avoid it.

After removing the  from our imports we can see an error:

Error: Nest can’t resolve dependencies of the UserRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

To work around it, we need to provide a mocked User repository. To do so, we need to use the   from  .

Unfortunately, the above error persists. This is because we imported   that contains . We should avoid importing our modules when writing unit tests because we don’t want to test integration between classes just yet. We need to add   to our providers instead.

src/authentication/tests/authentication.service.spec.ts

The object we put into   above is our mocked repository. We add some methods to it later below.

Mocking ConfigService and JwtService

Since we want to avoid using modules, we also can replace  and  with mocks. To be more precise, we need to provide mocked   and  .

A clean approach to that would be to create separate files for the above mocks.

src/utils/mocks/config.service.ts

src/utils/mocks/jwt.service.ts

When we use the above, our test now looks like that:

src/utils/mocks/config.service.ts

Changing the mock per test

We do not always want to mock something the same way in each test. To change our implementation between tests, we can use  .

src/users/tests/users.service.spec.ts

Summary

In this article, we’ve looked into how to write unit tests in NestJS. To do so, we’ve used the Jest library that comes bundled with NestJS. We’ve also used some of the built-in utilities to mock various services and modules properly. One of the most important ones was mocking the database connection so that we can keep our tests isolated.

Series Navigation<< API with NestJS #7. Creating relationships with Postgres and TypeORMAPI with NestJS #9. Testing services and controllers with integration tests >>
Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Altaf
Altaf
3 years ago

amazing tutorials, thank you so much

shiro t
shiro t
2 years ago

thanks for the helpful contents

https://github.com/mwanago/nestjs-typescript/blob/master/src/users/tests/users.service.spec.ts

retuns error do you have any suggestion
—–

   Nest can’t resolve dependencies of the UsersService (UserRepository, ?, Connection, StripeService, LocalFilesService). Please make sure that the argument DatabaseFilesService at index [1] is available in the RootTestModule context.

  Potential solutions:
  – If DatabaseFilesService is a provider, is it part of the current RootTestModule?
  – If DatabaseFilesService is exported from a separate @Module, is that module imported within RootTestModule?
   @Module({
    imports: [ /* the Module containing DatabaseFilesService */ ]
   })

Salman Saif
Salman Saif
2 years ago
Reply to  shiro t

You need to create a mock service for ‘DatabaseFilesService’, ‘StripeService’ & ‘localFilesService’.
In your providers array, do this for all 3 services:
{
      provide: DatabaseFilesService,
      useClass: FakeDatabaseFilesService,
}

and create a class for each fake service and define all methods of it like:
export class FakeDatabaseFilesService {
  public async find(): Promise<void> {}
}

soonyeop
soonyeop
1 year ago

this article use typeorm version ^0.2.24. and my version is ^0.3.14. when I create UserService Instance, I have a problem with argument Repository<User>(). this argument create error that expect 2-3 argment(targetEntity, EntityManager, options). How can i solve this??

Alex
Alex
1 year ago
Reply to  soonyeop

    new UsersService(
        dataSource.getRepository(User),
        dataSource.getRepository(Address),
    ), use your datasourse – typeOrm.comfig.ts

Amir
Amir
1 year ago
Reply to  soonyeop

You should use Test.createTestingModule() instead of manually doing the dependency injection. Wanago used that in the very next section.