Consider an Express app test suite that opens a database connection before tests but does not close it after. What is the likely outcome?
Think about what happens when a Node.js process has open resources.
If the database connection remains open, Node.js keeps the event loop active, causing tests to hang or timeout instead of exiting.
Choose the code that properly opens a database connection before tests and closes it after all tests run.
Look for async functions that run once before and after all tests.
beforeAll and afterAll run once before and after all tests, ideal for opening and closing database connections. Using beforeEach/afterEach opens and closes connections for every test, which is inefficient.
Review the test setup code below and identify the cause of the timeout error.
beforeAll(() => {
db.connect();
});
afterAll(() => {
db.disconnect();
});
test('sample test', () => {
expect(true).toBe(true);
});Consider how asynchronous code should be handled in test lifecycle hooks.
Without async/await or returning a promise, beforeAll and afterAll finish immediately, but the database connection is still pending, causing the test runner to wait indefinitely and timeout.
Given the following code, what will be the state of the test database after all tests complete?
beforeAll(async () => { await db.connect(); await db.clear(); }); afterAll(async () => { await db.disconnect(); });
Look at what happens before and after all tests regarding connection and data.
The beforeAll hook connects and clears the database, ensuring it is empty before tests. The afterAll hook disconnects, closing the connection. So after tests, the database is empty and connection closed.
Explain the main reason for using separate test database setup and teardown processes instead of running tests against the production database.
Think about the risks of running tests on live data.
Running tests on production databases risks corrupting or deleting real data. Isolating test databases protects production data and allows safe, repeatable tests.