NestJs Testing

Testing with NestJS and Jest

NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It uses modern JavaScript, built with and fully supporting TypeScript. Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using Babel, TypeScript, Node.js, React, Angular, Vue.js, and more.

This documentation will guide you through the process of setting up and writing tests for your NestJS application using Jest.

Setting Up Testing Environment

NestJS comes with Jest pre-configured, but you need to install the necessary packages:

pnpm add--save-dev jest @types/jest ts-jest @nestjs/testing

Configure Jest

Create a jest.config.js file in the root of your project with the following content:

module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: 'src',
  testRegex: '.*\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  collectCoverageFrom: [
    '**/*.(t|j)s'
  ],
  coverageDirectory: '../coverage',
  testEnvironment: 'node',
};

Writing Tests

Unit Testing

Unit tests focus on testing individual components or services. They ensure that each part of your application behaves as expected in isolation.

Example Service Test

Consider a simple CatsService:

Create a test file named cats.service.spec.ts:

Integration Testing

Integration tests ensure that different parts of the application work together as expected.

Example Controller Test

Consider a CatsController that uses the CatsService:

Create a test file named cats.controller.spec.ts:

E2E Testing

End-to-end (E2E) tests check the entire flow of your application, ensuring that all parts work together correctly.

Example E2E Test

NestJS provides a separate project structure for E2E tests. Create a test file named app.e2e-spec.ts in the test directory:

Running Tests

To run your tests, use the following command:

For E2E tests, use:

Conclusion

By setting up Jest with NestJS, you can write comprehensive tests that ensure the correctness of your application at different levels. Unit tests validate individual components, integration tests check the interaction between components, and E2E tests verify the application's behavior as a whole. Following these practices will help you maintain a robust and reliable codebase.

Last updated