0
0
NestJSframework~5 mins

Test database strategies in NestJS

Choose your learning style9 modes available
Introduction

Testing with a database helps ensure your app works well with real data. Using test databases keeps your real data safe and your tests reliable.

When you want to check if your database queries return correct results.
When you need to test how your app handles saving or updating data.
When you want to avoid messing up real data during tests.
When you want to run automated tests that include database operations.
When you want to simulate different database states for testing.
Syntax
NestJS
import { Test } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';

await Test.createTestingModule({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: ':memory:',
      entities: [YourEntity],
      synchronize: true,
    }),
    TypeOrmModule.forFeature([YourEntity]),
  ],
  providers: [YourService],
}).compile();

Use an in-memory database like SQLite for fast, isolated tests.

Set synchronize: true to auto-create tables during tests.

Examples
Sets up an in-memory SQLite database for quick tests without files.
NestJS
TypeOrmModule.forRoot({
  type: 'sqlite',
  database: ':memory:',
  entities: [User],
  synchronize: true,
})
Connects to a real Postgres test database for integration tests.
NestJS
TypeOrmModule.forRoot({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'test',
  password: 'test',
  database: 'test_db',
  entities: [User],
  synchronize: true,
})
Resets the test database before each test to keep tests independent.
NestJS
await connection.dropDatabase();
await connection.synchronize();
Sample Program

This example shows a NestJS test setup using an in-memory SQLite database. It creates a user and fetches all users to verify database operations work in tests.

NestJS
import { Test } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

@Injectable()
class UserService {
  constructor(
    @InjectRepository(User)
    private repo: Repository<User>,
  ) {}

  async createUser(name: string) {
    const user = this.repo.create({ name });
    return this.repo.save(user);
  }

  async findAll() {
    return this.repo.find();
  }
}

async function bootstrap() {
  const moduleRef = await Test.createTestingModule({
    imports: [
      TypeOrmModule.forRoot({
        type: 'sqlite',
        database: ':memory:',
        entities: [User],
        synchronize: true,
      }),
      TypeOrmModule.forFeature([User]),
    ],
    providers: [UserService],
  }).compile();

  const userService = moduleRef.get(UserService);

  await userService.createUser('Alice');
  const users = await userService.findAll();
  console.log(users);
}

bootstrap();
OutputSuccess
Important Notes

Use an in-memory database for fast tests that don't affect real data.

Reset the database state before each test to avoid test interference.

For complex tests, consider using a dedicated test database server.

Summary

Test databases keep your real data safe during testing.

In-memory databases like SQLite are fast and easy for tests.

Resetting the database before tests keeps tests independent and reliable.