Mocking database calls lets you test your code without needing a real database. It helps you check if your app works correctly and faster.
0
0
Mocking database calls in Express
Introduction
When you want to test your API routes without connecting to a real database.
When your database is slow or unavailable during development.
When you want to simulate different database responses like errors or empty results.
When writing automated tests to ensure your code handles data correctly.
When you want to develop frontend and backend separately without waiting for the database setup.
Syntax
Express
const mockDb = { getUser: () => Promise.resolve({ id: 1, name: 'Alice' }) };
app.get('/user', async (req, res) => {
const user = await mockDb.getUser();
res.json(user);
});Use simple objects or functions that return promises to mimic database calls.
Replace real database calls with mocks during testing or development.
Examples
This mock function simulates finding a user by ID and returns a promise with user data.
Express
const mockDb = {
findUserById: (id) => Promise.resolve({ id, name: 'Bob' })
};This mock simulates a database call that returns no users.
Express
const mockDb = {
getAllUsers: () => Promise.resolve([]) // returns empty list
};This mock simulates a database error to test error handling.
Express
const mockDb = {
getUser: () => Promise.reject(new Error('DB error'))
};Sample Program
This Express app uses a mock database call to return a user object when you visit /user. It shows how to replace real database calls with mocks for easy testing.
Express
import express from 'express'; const app = express(); // Mock database object const mockDb = { getUser: () => Promise.resolve({ id: 1, name: 'Alice' }) }; app.get('/user', async (req, res) => { try { const user = await mockDb.getUser(); res.json(user); } catch (error) { res.status(500).json({ error: 'Failed to get user' }); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Mocks should mimic the shape and behavior of real database calls as closely as possible.
Use mocking libraries like Sinon or Jest for more advanced mocking in tests.
Remember to switch back to real database calls in production code.
Summary
Mocking helps test code without a real database.
Use simple functions returning promises to simulate database calls.
Mocks improve development speed and test reliability.