Learn NestJS · 13/14

Ensuring Quality: Testing

10 min read

Ensuring Quality: Testing in NestJS 🧪

Welcome to the world of testing in NestJS! Think of writing code without tests as building a magnificent skyscraper without ever checking the foundation. It might look impressive, but you're in for a nerve-wracking surprise when the first gust of wind comes along. Testing is your quality assurance, your safety net, and your peace of mind, ensuring your application works as expected, now and in the future.

In this guide, we'll explore the different layers of testing in a NestJS application. We'll start with the smallest units of your code and gradually move to testing the application as a whole. So, grab your virtual hard hat, and let's build some confidence in our code!


Unit Testing Services and Logic with Jest 🔬

What is Unit Testing?

Unit testing is the practice of testing individual components or "units" of your application in isolation. Imagine you're building a car. A unit test would be like checking if the engine starts, the wheels turn, and the horn honks, all separately, before you even think about assembling the car.

The Problem It Solves

In a complex application, a small change in one part can unexpectedly break another. Unit tests help you catch these issues early by verifying that each piece of your code behaves correctly on its own. This makes debugging easier and your code more reliable.

Meet Jest: Your Testing Sidekick

NestJS comes with Jest, a delightful JavaScript testing framework, right out of the box. Jest is like that super-organized friend who loves to check everything twice, making sure all your code is in tip-top shape. It provides you with tools to write and run tests, and it gives you clear feedback on what's working and what's not.

Setting Up a Test for a Service

Let's say we have a CatsService that is responsible for our feline-related business logic.

typescript
// src/cats/cats.service.ts
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';

@Injectable()
export class CatsService {
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push(cat);
  }

  findAll(): Cat[] {
    return this.cats;
  }
}

When you generate a service using the NestJS CLI (nest generate service cats), it automatically creates a spec file for you (cats.service.spec.ts). How thoughtful!

Here's what a basic test file for our CatsService would look like:

typescript
// src/cats/cats.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { CatsService } from './cats.service';

describe('CatsService', () => {
  let service: CatsService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [CatsService],
    }).compile();

    service = module.get<CatsService>(CatsService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

Let's Break It Down:

  • describe: This is a way to group related tests. We're creating a suite of tests for our CatsService.
  • beforeEach: This function runs before each test in the describe block. It's the perfect place to set up a fresh instance of our CatsService for each test to ensure they are independent.
  • Test.createTestingModule: This is the star of the show. It creates a testing module that mirrors our actual NestJS module, allowing us to instantiate our service and its dependencies.
  • it: This is where the actual test happens. The first argument is a description of what the test should do.
  • expect: This is a Jest function that lets you make assertions. expect(service).toBeDefined() checks if our service was successfully created.

Testing the Logic

Now, let's test the actual methods of our CatsService.

typescript
// src/cats/cats.service.spec.ts
// ... (imports and describe block)

  it('should create a cat', () => {
    const cat: Cat = { name: 'Test Cat', age: 1, breed: 'Test Breed' };
    service.create(cat);
    expect(service.findAll()).toContain(cat);
  });

  it('should return all cats', () => {
    const cat1: Cat = { name: 'Cat 1', age: 2, breed: 'Breed 1' };
    const cat2: Cat = { name: 'Cat 2', age: 3, breed: 'Breed 2' };
    service.create(cat1);
    service.create(cat2);
    expect(service.findAll()).toEqual([cat1, cat2]);
    expect(service.findAll().length).toBe(2);
  });

To run your tests, simply use the command:

bash
npm run test

Jest will then run all the .spec.ts files in your project and give you a neat summary of the results.


Mocking Dependencies and Database Repositories 🎭

What is Mocking?

Mocking is the process of creating a "fake" version of a dependency in your tests. Think of a movie stunt double. You don't want your star actor to actually jump out of a burning building, so you bring in a professional to pretend to be the actor for that scene. In testing, you don't want your unit tests to depend on external systems like databases or other services, so you create mocks to simulate their behavior.

The Problem It Solves

Unit tests should be fast and isolated. If your CatsService test actually connects to a real database, it becomes slow and dependent on the database's state. Mocking allows you to test your service's logic without these external dependencies, making your tests faster and more reliable.

Mocking a Repository

Let's imagine our CatsService now uses a CatRepository to interact with a database.

typescript
// src/cats/cats.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cat } from './entities/cat.entity';

@Injectable()
export class CatsService {
  constructor(
    @InjectRepository(Cat)
    private catsRepository: Repository<Cat>,
  ) {}

  findAll(): Promise<Cat[]> {
    return this.catsRepository.find();
  }
}

To test this service in isolation, we need to mock the Repository<Cat>.

typescript
// src/cats/cats.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CatsService } from './cats.service';
import { Cat } from './entities/cat.entity';

describe('CatsService', () => {
  let service: CatsService;
  let repository: Repository<Cat>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CatsService,
        {
          provide: getRepositoryToken(Cat),
          useValue: {
            find: jest.fn().mockResolvedValue([]),
            // ... mock other repository methods as needed
          },
        },
      ],
    }).compile();

    service = module.get<CatsService>(CatsService);
    repository = module.get<Repository<Cat>>(getRepositoryToken(Cat));
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('should return an array of cats', async () => {
    const testCats: Cat[] = [{ id: 1, name: 'Test Cat', age: 2, breed: 'Test Breed' }];
    jest.spyOn(repository, 'find').mockResolvedValue(testCats);

    expect(await service.findAll()).toBe(testCats);
  });
});

What's Happening Here?

  • getRepositoryToken(Cat): This is a utility function from @nestjs/typeorm that gets the injection token for the Cat repository.
  • useValue: We provide a mock object for the repository. This object has the same methods as the real repository (find, findOne, save, etc.), but we use jest.fn() to create mock functions.
  • mockResolvedValue([]): We are telling our mock find method to return a resolved promise with an empty array.
  • jest.spyOn(repository, 'find').mockResolvedValue(testCats): In our test case, we can further customize the behavior of our mock. Here, we're making the find method return a specific array of cats for this particular test.

By mocking the repository, we can test our service's logic without ever touching a real database. It's like having a rehearsal with stand-in actors before the big show!


Unit Testing Controllers and HTTP Responses 🚦

What is Controller Unit Testing?

This type of testing focuses on the controllers of your application. Controllers are the traffic cops of your NestJS app; they handle incoming requests and send back responses. Unit testing controllers ensures that they call the right services and return the correct HTTP status codes and data.

The Problem It Solves

You want to make sure your API endpoints behave as expected. For example, a POST request to /cats should create a new cat and return a 201 Created status code. Controller tests verify this behavior without making actual HTTP requests.

Testing a Controller

Let's look at a CatsController.

typescript
// src/cats/cats.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CreateCatDto } from './dto/create-cat.dto';
import { Cat } from './interfaces/cat.interface';

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll();
  }
}

Now, let's write a test for this controller.

typescript
// src/cats/cats.controller.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

describe('CatsController', () => {
  let controller: CatsController;
  let service: CatsService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [
        {
          provide: CatsService,
          useValue: {
            findAll: jest.fn().mockResolvedValue([]),
            create: jest.fn(),
          },
        },
      ],
    }).compile();

    controller = module.get<CatsController>(CatsController);
    service = module.get<CatsService>(CatsService);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });

  describe('findAll', () => {
    it('should return an array of cats', async () => {
      const result: Cat[] = [{ name: 'Test', age: 1, breed: 'Test' }];
      jest.spyOn(service, 'findAll').mockResolvedValue(result);

      expect(await controller.findAll()).toBe(result);
    });
  });

  describe('create', () => {
    it('should create a cat', async () => {
      const createCatDto: CreateCatDto = { name: 'Test Cat', age: 1, breed: 'Breed' };
      await controller.create(createCatDto);
      expect(service.create).toHaveBeenCalledWith(createCatDto);
    });
  });
});

Key Concepts:

  • Mocking the Service: Notice that we are providing a mock for CatsService. This is because we only want to test the controller's logic, not the service's logic (we already did that in our service unit tests!).
  • Spying on Methods: We use jest.spyOn to check if the controller's methods call the service's methods with the correct arguments.

This approach ensures that our controller correctly delegates tasks to the service layer.


End-to-End (e2e) Testing using Supertest 🌐

What is End-to-End Testing?

End-to-end (e2e) testing is the final frontier of testing. It involves testing your application from start to finish, just like a real user would. In the context of a NestJS API, this means making actual HTTP requests to your endpoints and checking the responses.

The Problem It Solves

While unit tests are great for testing individual components, they don't guarantee that all the pieces will work together harmoniously. E2E tests verify the entire application flow, from the incoming request, through the controllers and services, to the database and back. It's the ultimate confidence booster!

Supertest to the Rescue!

NestJS uses Supertest, a library that makes it easy to test HTTP servers. When you create a new NestJS project, it comes with a pre-configured e2e test setup.

Here's an example of an e2e test for our CatsController:

typescript
// test/cats.e2e-spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { CatsModule } from '../src/cats/cats.module';
import { TypeOrmModule } from '@nestjs/typeorm';

describe('CatsController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        CatsModule,
        // Set up an in-memory database for testing
        TypeOrmModule.forRoot({
          type: 'sqlite',
          database: ':memory:',
          entities: [__dirname + '/../**/*.entity{.ts,.js}'],
          synchronize: true,
        }),
      ],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/cats (GET)', () => {
    return request(app.getHttpServer())
      .get('/cats')
      .expect(200)
      .expect([]);
  });

  afterAll(async () => {
    await app.close();
  });
});

Let's Unpack This:

  • INestApplication: We create an entire NestJS application instance for our e2e tests.
  • app.getHttpServer(): This gives us the underlying HTTP server that we can make requests to.
  • request(...): This is the Supertest function that initiates an HTTP request.
  • .get('/cats'): We are making a GET request to the /cats endpoint.
  • .expect(200): We assert that the HTTP status code should be 200 (OK).
  • .expect([]): We assert that the response body should be an empty array.

To run e2e tests, you use the command:

bash
npm run test:e2e

E2E tests are slower than unit tests, but they provide invaluable confidence that your application is working as a cohesive whole.

📚 Further Reading and References

Challenge

You are tasked with writing a unit test for the UsersController. The controller has a dependency on UsersService to fetch user data.

Your goal is to test the findOne method of the UsersController. You must ensure that the test is isolated and does not actually call the real UsersService.

Requirements:

  1. Inside the beforeEach block, set up a testing module using Test.createTestingModule.
  2. The testing module's configuration should include UsersController in its controllers array.
  3. Provide a mock implementation for UsersService in the providers array. The mock should define a findOne method using jest.fn().
  4. In the test case for the findOne method, define a sample user object and a user ID.
  5. Use a Jest spy (jest.spyOn) to control the return value of the mocked UsersService.findOne method. Make it resolve with the sample user object.
  6. Call the controller.findOne method using the sample user ID.
  7. Assert that the UsersService.findOne method was called exactly once and with the correct user ID.
  8. Assert that the result returned by controller.findOne matches the sample user object you defined.

Expected result

Your solution should be a complete TypeScript test file that correctly unit tests the UsersController's findOne method.

The final code must satisfy the following criteria:

  • The Test.createTestingModule method is called inside beforeEach with a configuration object.
  • The configuration object contains a controllers property with [UsersController].
  • The configuration object contains a providers property that mocks UsersService. The mock should be provided using { provide: UsersService, useValue: { findOne: jest.fn() } }.
  • The it block for the findOne test contains:
    • A constant defining a sample UserDto object (e.g., { id: '1', name: 'Test User', email: '[email protected]' }).
    • A call to jest.spyOn(service, 'findOne').mockResolvedValue(sampleUser) to mock the service method's return value.
    • An await call to controller.findOne('1').
    • An assertion expect(service.findOne).toHaveBeenCalledWith('1') to check if the service was called correctly.
    • An assertion expect(await controller.findOne('1')).toEqual(sampleUser) to check if the controller returned the correct data.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.