Setting up and tearing down a test database helps keep tests clean and reliable. It makes sure each test starts fresh without leftover data.
0
0
Test database setup and teardown in Express
Introduction
When you want to test API routes that read or write data.
When you need to isolate tests so they don't affect each other.
When you want to reset the database state before each test.
When you want to clean up resources after tests finish.
Syntax
Express
beforeAll(async () => { // Connect to test database }); afterAll(async () => { // Disconnect and clean up }); beforeEach(async () => { // Prepare fresh data }); afterEach(async () => { // Clear data });
beforeAll runs once before all tests start.
afterAll runs once after all tests finish.
Examples
Connects to a MongoDB test database before running tests.
Express
beforeAll(async () => { await db.connect('mongodb://localhost/testdb'); });
Disconnects from the database after all tests complete.
Express
afterAll(async () => { await db.disconnect(); });
Clears all data before each test to start fresh.
Express
beforeEach(async () => { await db.clearCollections(); });
Sample Program
This example uses an in-memory MongoDB to run tests without a real database. It connects before tests, clears data before each test, and disconnects after all tests. It shows adding and fetching users to confirm setup works.
Express
import express from 'express'; import request from 'supertest'; import mongoose from 'mongoose'; import { MongoMemoryServer } from 'mongodb-memory-server'; const app = express(); app.use(express.json()); const userSchema = new mongoose.Schema({ name: String }); const User = mongoose.model('User', userSchema); app.post('/users', async (req, res) => { const user = new User({ name: req.body.name }); await user.save(); res.status(201).json(user); }); app.get('/users', async (req, res) => { const users = await User.find(); res.json(users); }); let mongoServer; beforeAll(async () => { mongoServer = await MongoMemoryServer.create(); const uri = mongoServer.getUri(); await mongoose.connect(uri); }); afterAll(async () => { await mongoose.disconnect(); await mongoServer.stop(); }); beforeEach(async () => { await User.deleteMany(); }); // Example test (async () => { // Add a user await request(app).post('/users').send({ name: 'Alice' }).expect(201); // Get users const res = await request(app).get('/users').expect(200); console.log(res.body); // Clear users await User.deleteMany(); // Get users again const res2 = await request(app).get('/users').expect(200); console.log(res2.body); })();
OutputSuccess
Important Notes
Use an in-memory database like mongodb-memory-server for fast, isolated tests.
Always clear data before each test to avoid test interference.
Disconnect and stop the database after tests to free resources.
Summary
Setup and teardown keep tests independent and reliable.
Use beforeAll and afterAll to manage database connection.
Use beforeEach and afterEach to reset data.