Bird
Raised Fist0
NestJSframework~20 mins

Test database strategies in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Test Database Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when using an in-memory database for NestJS tests?
You configure your NestJS tests to use an in-memory database like SQLite in memory mode. What is the main behavior you will observe during test runs?
AData from previous test runs remains in the database, causing tests to share state.
BEach test run starts with a fresh empty database, so no data persists between tests.
CThe database runs on disk and requires manual cleanup after tests.
DThe in-memory database automatically syncs with the production database.
Attempts:
2 left
💡 Hint

Think about what 'in-memory' means for data persistence.

📝 Syntax
intermediate
2:00remaining
Which NestJS testing setup correctly resets the test database before each test?
Given the following NestJS test setup, which option correctly resets the database before each test?
NestJS
beforeEach(async () => {
  // reset database here
});
Aawait connection.synchronize(true);
Bawait connection.clear();
Cawait connection.dropDatabase(); await connection.synchronize();
Dawait connection.close();
Attempts:
2 left
💡 Hint

Resetting means removing all tables and recreating them.

🔧 Debug
advanced
2:00remaining
Why does the NestJS test suite fail when using a shared test database without cleanup?
You run your NestJS tests using a shared test database but do not clean data between tests. Tests start failing with unique constraint errors. What is the cause?
AThe test runner does not support parallel execution.
BThe database connection is closed too early causing errors.
CThe test database schema is not synchronized with entities.
DTests share data causing conflicts because previous test data remains in the database.
Attempts:
2 left
💡 Hint

Think about what happens if data is not cleared between tests.

🧠 Conceptual
advanced
2:00remaining
What is the advantage of using transactions in NestJS test database strategies?
Why might you wrap each NestJS test in a database transaction that is rolled back after the test?
AIt isolates test data changes and automatically reverts them, keeping the database clean.
BIt speeds up tests by caching database queries.
CIt permanently saves test data for debugging after tests finish.
DIt allows tests to share data between each other for faster setup.
Attempts:
2 left
💡 Hint

Think about how transactions can undo changes.

❓ state_output
expert
3:00remaining
What is the final count of users in the test database after running this NestJS test code?
Consider this NestJS test code using TypeORM with an in-memory SQLite database. What is the number of users in the database after the test completes?
NestJS
it('adds users and rolls back', async () => {
  await connection.transaction(async manager => {
    await manager.save(User, { name: 'Alice' });
    await manager.save(User, { name: 'Bob' });
    const countInside = await manager.count(User);
    expect(countInside).toBe(2);
    throw new Error('Rollback');
  }).catch(() => {});
  const countAfter = await connection.manager.count(User);
  expect(countAfter).toBe(0);
});
A0 users, because the transaction was rolled back.
B1 user, because only the first save succeeded.
C2 users, because the users were saved before the error.
DTest fails with an unhandled error.
Attempts:
2 left
💡 Hint

What happens to data inside a transaction if an error is thrown?

Practice

(1/5)
1.

Why do we use a separate test database in NestJS applications?

easy
A. To store user passwords securely
B. To keep real data safe and avoid accidental changes during tests
C. To make the application run faster in production
D. To reduce the size of the main database

Solution

  1. Step 1: Understand the purpose of test databases

    Test databases are used to isolate testing data from real data to prevent accidental data loss or corruption.
  2. Step 2: Identify the main reason for using test databases in NestJS

    Using a separate test database ensures tests do not affect production data, keeping it safe.
  3. Final Answer:

    To keep real data safe and avoid accidental changes during tests -> Option B
  4. Quick Check:

    Test database = Protect real data [OK]
Hint: Test DB isolates test data from real data [OK]
Common Mistakes:
  • Thinking test DB improves production speed
  • Confusing test DB with security for passwords
  • Assuming test DB reduces main DB size
2.

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,
})
easy
A. 'test.db'
B. 'memory.db'
C. ':disk:'
D. ':memory:'

Solution

  1. Step 1: Recall SQLite in-memory database syntax

    SQLite uses ':memory:' as the special name to create a temporary in-memory database.
  2. Step 2: Match the correct database name in the config

    Using ':memory:' tells TypeORM to use an in-memory DB for fast, isolated tests.
  3. Final Answer:

    ':memory:' -> Option D
  4. Quick Check:

    SQLite in-memory DB = ':memory:' [OK]
Hint: SQLite in-memory DB uses ':memory:' string [OK]
Common Mistakes:
  • Using a file name instead of ':memory:'
  • Confusing ':disk:' as valid SQLite option
  • Using arbitrary file names like 'memory.db'
3.

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);
});
medium
A. 1
B. 0
C. 2
D. undefined

Solution

  1. Step 1: Understand what synchronize(true) does

    Calling synchronize(true) resets the database, clearing all data before each test.
  2. Step 2: Analyze the data saved before the test

    After reset, two users 'Alice' and 'Bob' are saved, so the DB has 2 users.
  3. Step 3: Check the find() result

    Finding all users returns an array of length 2.
  4. Final Answer:

    2 -> Option C
  5. Quick Check:

    Reset + save 2 users = 2 users found [OK]
Hint: Reset DB then save 2 users means find() returns 2 [OK]
Common Mistakes:
  • Assuming DB is not reset and counting old data
  • Thinking synchronize(true) deletes data after save
  • Expecting undefined because of async confusion
4.

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);
});
medium
A. Database is reset only once before all tests, causing data to persist between tests
B. Connection is closed before tests run
C. User repository is not defined
D. Tests run synchronously causing race conditions

Solution

  1. Step 1: Analyze when the database reset happens

    Database reset with synchronize(true) is done only once before all tests, not before each test.
  2. Step 2: Understand test data persistence

    Data saved in the first test remains in the DB during the second test, causing unexpected results.
  3. Final Answer:

    Database is reset only once before all tests, causing data to persist between tests -> Option A
  4. Quick Check:

    Reset once beforeAll causes data carryover [OK]
Hint: Reset DB before each test to avoid data carryover [OK]
Common Mistakes:
  • Thinking connection closes too early
  • Assuming userRepository is undefined
  • Believing tests run in parallel causing race
5.

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?

  1. Use TypeOrmModule.forRoot with database: ':memory:'
  2. Reset the database schema before each test
  3. Close and reopen the connection before each test
  4. Seed only required test data inside each test

Which combination of these steps is best practice?

hard
A. All steps 1, 2, 3, and 4
B. 1 and 3 only
C. 2, 3, and 4 only
D. 1, 2, and 4 only

Solution

  1. Step 1: Use in-memory DB for fast isolated tests

    Setting database to ':memory:' creates a fresh DB in memory for each connection.
  2. Step 2: Reset schema before each test

    Resetting schema ensures no leftover data or schema changes affect tests.
  3. Step 3: Close and reopen connection before each test

    Reopening connection resets the in-memory DB state fully.
  4. Step 4: Seed only needed data per test

    Seeding minimal data keeps tests independent and fast.
  5. Final Answer:

    All steps 1, 2, 3, and 4 -> Option A
  6. Quick Check:

    Full reset + seed per test = reliable tests [OK]
Hint: Combine in-memory DB, reset, reconnect, and seed per test [OK]
Common Mistakes:
  • Skipping connection reopen causing stale DB
  • Not resetting schema before tests
  • Seeding too much data globally
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard