Performance: Test database strategies
This affects the speed and reliability of backend tests, impacting developer feedback loops and CI pipeline efficiency.
Use an in-memory database like SQLite or a dedicated test database with proper setup and teardown.
Use the production database directly for tests without isolation or cleanup.
| Pattern | Test Speed | Isolation | Resource Usage | Verdict |
|---|---|---|---|---|
| Using production DB without isolation | Very slow | No | High | [X] Bad |
| In-memory DB with transactions | Fast | Yes | Low | [OK] Good |
| Dropping schema each test | Slow | Yes | High | [X] Bad |
| Using minimal fixtures | Fast | Yes | Low | [OK] Good |
Why do we use a separate test database in NestJS applications?
Which of the following is the correct way to configure an in-memory SQLite database for testing in a NestJS TypeOrmModule?
TypeOrmModule.forRoot({
type: 'sqlite',
database: ???,
entities: [User],
synchronize: true,
})Given this NestJS test setup snippet, what will be the output of console.log(users.length) inside the test?
beforeEach(async () => {
await connection.synchronize(true); // resets DB
await userRepository.save([{ name: 'Alice' }, { name: 'Bob' }]);
});
test('users count', async () => {
const users = await userRepository.find();
console.log(users.length);
});What is the main problem with this test database setup code snippet?
beforeAll(async () => {
await connection.synchronize(true);
});
afterAll(async () => {
await connection.close();
});
test('should save user', async () => {
await userRepository.save({ name: 'Charlie' });
const users = await userRepository.find();
expect(users.length).toBe(1);
});
test('should find no users initially', async () => {
const users = await userRepository.find();
expect(users.length).toBe(0);
});You want to ensure each test in your NestJS app runs with a clean database state using an in-memory SQLite DB. Which strategy best achieves this?
TypeOrmModule.forRoot with database: ':memory:'Which combination of these steps is best practice?
Pass the test and this pattern moves unknown