Bird
Raised Fist0
Expressframework~20 mins

Test database setup and teardown in Express - 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 if the test database connection is not closed after tests?

Consider an Express app test suite that opens a database connection before tests but does not close it after. What is the likely outcome?

AThe database will automatically close the connection after tests finish.
BTests will run faster because the connection stays open for reuse.
CTests may hang or timeout because the open connection prevents the process from exiting.
DNo effect; tests complete normally and exit immediately.
Attempts:
2 left
💡 Hint

Think about what happens when a Node.js process has open resources.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly sets up and tears down a test database connection in Express tests?

Choose the code that properly opens a database connection before tests and closes it after all tests run.

Abefore(() => { db.connect(); }); after(() => { db.disconnect(); });
BbeforeAll(async () => { await db.connect(); }); afterAll(async () => { await db.disconnect(); });
CbeforeEach(async () => { await db.connect(); }); afterEach(async () => { await db.disconnect(); });
Dsetup(() => { db.connect(); }); teardown(() => { db.disconnect(); });
Attempts:
2 left
💡 Hint

Look for async functions that run once before and after all tests.

🔧 Debug
advanced
2:00remaining
Why does this test suite fail with 'Timeout - Async callback was not invoked' error?

Review the test setup code below and identify the cause of the timeout error.

Express
beforeAll(() => {
  db.connect();
});

afterAll(() => {
  db.disconnect();
});

test('sample test', () => {
  expect(true).toBe(true);
});
AThe beforeAll and afterAll functions are missing async/await, so the test runner does not wait for connection to finish.
BThe test function is missing async keyword, causing the test to timeout.
CThe db.connect() and db.disconnect() functions are synchronous and block the event loop.
DThe test suite is missing a call to jest.runAllTimers() to complete async operations.
Attempts:
2 left
💡 Hint

Consider how asynchronous code should be handled in test lifecycle hooks.

❓ state_output
advanced
2:00remaining
What is the state of the test database after running this setup and teardown code?

Given the following code, what will be the state of the test database after all tests complete?

Express
beforeAll(async () => {
  await db.connect();
  await db.clear();
});

afterAll(async () => {
  await db.disconnect();
});
AThe database connection remains open and the database still contains old data.
BThe database connection remains open and the database is cleared.
CThe database connection is closed but the database still contains old data.
DThe database connection is closed and the database is empty (cleared).
Attempts:
2 left
💡 Hint

Look at what happens before and after all tests regarding connection and data.

🧠 Conceptual
expert
2:00remaining
Why is it important to isolate test database setup and teardown from production database in Express apps?

Explain the main reason for using separate test database setup and teardown processes instead of running tests against the production database.

ATo prevent tests from accidentally modifying or deleting real production data, ensuring data safety.
BBecause test databases automatically generate fake data, unlike production databases.
CTo improve test speed by using a smaller production database copy.
DBecause production databases do not support connections from test suites.
Attempts:
2 left
💡 Hint

Think about the risks of running tests on live data.

Practice

(1/5)
1. What is the main purpose of setting up a test database connection before running tests in an Express app?
easy
A. To speed up the app by using a faster database
B. To ensure tests run against a separate database without affecting real data
C. To automatically deploy the app after tests
D. To backup the production database

Solution

  1. Step 1: Understand test database role

    The test database is used to isolate test data from real production data to avoid accidental changes.
  2. Step 2: Purpose of setup connection

    Setting up a connection before tests ensures all tests use this separate database environment.
  3. Final Answer:

    To ensure tests run against a separate database without affecting real data -> Option B
  4. Quick Check:

    Test DB isolates data = A [OK]
Hint: Test DB isolates data from production [OK]
Common Mistakes:
  • Confusing test DB with production DB
  • Thinking setup speeds app
  • Assuming setup deploys app
2. Which of the following is the correct way to close a MongoDB connection in an Express test teardown using Mongoose?
easy
A. mongoose.close()
B. mongoose.stop()
C. mongoose.end()
D. mongoose.disconnect()

Solution

  1. Step 1: Recall Mongoose connection methods

    Mongoose uses the method disconnect() to close the connection properly.
  2. Step 2: Verify method names

    Methods like close(), end(), or stop() do not exist on the mongoose object for disconnecting.
  3. Final Answer:

    mongoose.disconnect() -> Option D
  4. Quick Check:

    Disconnect method is disconnect() = B [OK]
Hint: Use mongoose.disconnect() to close connection [OK]
Common Mistakes:
  • Using nonexistent methods like close()
  • Confusing disconnect() with close()
  • Forgetting to await disconnect in async tests
3. Given this Express test setup code snippet using Jest and Mongoose:
beforeAll(async () => {
  await mongoose.connect('mongodb://localhost/testdb');
});
afterAll(async () => {
  await mongoose.disconnect();
});
test('database is empty before test', async () => {
  const count = await User.countDocuments();
  expect(count).toBe(0);
});

What will the test output if the test database has leftover users from previous tests?
medium
A. Test fails because count is not zero
B. Test passes because count is always zero
C. Test throws a connection error
D. Test skips because no users collection

Solution

  1. Step 1: Analyze test setup and test code

    The test connects to the test database but does not clear data before running the test.
  2. Step 2: Effect of leftover data

    If leftover users exist, User.countDocuments() returns a number greater than zero, causing expect(count).toBe(0) to fail.
  3. Final Answer:

    Test fails because count is not zero -> Option A
  4. Quick Check:

    Leftover data causes count > 0 = D [OK]
Hint: Leftover data breaks zero count tests [OK]
Common Mistakes:
  • Assuming test DB auto-clears data
  • Expecting count to be zero without cleanup
  • Ignoring async connection setup
4. You wrote this teardown code in your Express test:
afterEach(async () => {
  await mongoose.connection.dropDatabase();
  await mongoose.disconnect();
});

What is the main problem with this teardown approach?
medium
A. afterEach should be beforeAll for teardown
B. dropDatabase() does not clear collections
C. Disconnecting after each test causes connection errors in next tests
D. Missing await before dropDatabase()

Solution

  1. Step 1: Understand teardown timing

    Calling mongoose.disconnect() after each test closes the connection, but next tests expect it open.
  2. Step 2: Effect on subsequent tests

    Subsequent tests will fail because the database connection is closed and not reopened automatically.
  3. Final Answer:

    Disconnecting after each test causes connection errors in next tests -> Option C
  4. Quick Check:

    Disconnect once after all tests = C [OK]
Hint: Disconnect once after all tests, not after each [OK]
Common Mistakes:
  • Disconnecting inside afterEach instead of afterAll
  • Assuming dropDatabase clears connection
  • Forgetting async/await keywords
5. You want to ensure each test in your Express app runs with a clean test database. Which setup and teardown pattern is best?
1. Connect once before all tests
2. Clear data before each test
3. Disconnect once after all tests

Why is this pattern preferred?
hard
A. It keeps connection open for speed and clears data to isolate tests
B. It reconnects for each test to avoid stale connections
C. It disconnects before each test to reset state
D. It clears data only after all tests to save time

Solution

  1. Step 1: Analyze connection management

    Connecting once before all tests avoids overhead of reconnecting repeatedly, improving speed.
  2. Step 2: Analyze data clearing strategy

    Clearing data before each test ensures tests do not affect each other, keeping them isolated and reliable.
  3. Step 3: Analyze disconnect timing

    Disconnecting once after all tests properly closes resources without interrupting test flow.
  4. Final Answer:

    It keeps connection open for speed and clears data to isolate tests -> Option A
  5. Quick Check:

    Connect once, clear each test, disconnect once = A [OK]
Hint: Connect once, clear before each test, disconnect once [OK]
Common Mistakes:
  • Disconnecting too often causing errors
  • Not clearing data between tests
  • Reconnecting for every test slowing tests
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