Performance: Test database setup and teardown
This affects the speed and reliability of test execution, impacting developer feedback time and CI pipeline efficiency.
beforeAll(async () => { await db.connect(); await db.createCollections(); await db.seedTestData(); }); afterAll(async () => { await db.dropDatabase(); await db.disconnect(); }); beforeEach(async () => { await db.clearCollections(); });
beforeEach(async () => { await db.dropDatabase(); await db.createCollections(); await db.seedTestData(); }); afterEach(async () => { await db.dropDatabase(); });
| Pattern | DB Operations | Test Runtime Impact | Resource Usage | Verdict |
|---|---|---|---|---|
| Drop and recreate DB per test | High (drop + create each test) | Very slow (seconds per test) | High (many DB calls) | [X] Bad |
| Setup once, clear data per test | Moderate (clear collections only) | Fast (milliseconds per test) | Low (fewer DB calls) | [OK] Good |
disconnect() to close the connection properly.close(), end(), or stop() do not exist on the mongoose object for disconnecting.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);
});User.countDocuments() returns a number greater than zero, causing expect(count).toBe(0) to fail.afterEach(async () => {
await mongoose.connection.dropDatabase();
await mongoose.disconnect();
});mongoose.disconnect() after each test closes the connection, but next tests expect it open.1. Connect once before all tests
2. Clear data before each test
3. Disconnect once after all tests
Pass the test and this pattern moves unknown