What if you could test your app without ever touching the real database?
Why Mocking database calls in Express? - Purpose & Use Cases
Imagine you are building an Express app and need to test your routes that fetch data from a database. Every time you run tests, you must connect to the real database, wait for responses, and clean up test data manually.
Manually connecting to a real database during tests is slow, unreliable, and can cause flaky tests if the database is down or data changes unexpectedly. It also makes tests hard to run anywhere, like on a teammate's computer or a CI server.
Mocking database calls means replacing real database queries with fake ones that return preset data instantly. This makes tests fast, stable, and independent from the real database.
app.get('/users', (req, res) => { db.query('SELECT * FROM users', (err, results) => { if (err) res.status(500).send('Error'); else res.json(results); }); });
const mockDb = { query: (sql, cb) => cb(null, [{ id: 1, name: 'Alice' }]) };
app.get('/users', (req, res) => {
mockDb.query('SELECT * FROM users', (err, results) => {
if (err) res.status(500).send('Error');
else res.json(results);
});
});Mocking database calls enables you to write fast, reliable tests that run anywhere without needing a real database connection.
When developing a new feature, you can mock database calls to test your API routes quickly without waiting for the database or worrying about test data cleanup.
Manual database testing is slow and fragile.
Mocking replaces real calls with fast, fake responses.
This leads to reliable, fast tests that run anywhere.
Practice
Solution
Step 1: Understand mocking concept
Mocking means creating fake versions of parts of your app, like database calls, to test without real dependencies.Step 2: Identify the purpose in testing
Mocking database calls allows testing code logic without needing a real database, making tests faster and more reliable.Final Answer:
To test code without needing a real database connection -> Option AQuick Check:
Mocking = Test without real DB [OK]
- Thinking mocking speeds up production DB
- Confusing mocking with permanent DB replacement
- Assuming mocking changes real data storage
Solution
Step 1: Understand promise returning function
A mock database call should return a promise that resolves to data, so Promise.resolve is correct.Step 2: Check each option
const mockDbCall = Promise.resolve({ id: 1, name: 'Test' }); assigns a resolved promise directly, making mockDbCall a promise object not a callable function. const mockDbCall = () => { return { id: 1, name: 'Test' }; }; returns plain object, not a promise. const mockDbCall = () => Promise.resolve({ id: 1, name: 'Test' }); returns a function returning a resolved promise, correct. const mockDbCall = () => new Promise({ id: 1, name: 'Test' }); incorrectly uses new Promise without executor function.Final Answer:
const mockDbCall = () => Promise.resolve({ id: 1, name: 'Test' }); -> Option DQuick Check:
Promise.resolve returns a resolved promise [OK]
- Returning plain object instead of a promise
- Using new Promise without executor function
- Assigning a promise directly instead of a function returning it
getUser().then(console.log) output?const getUser = () => Promise.resolve({ id: 5, name: 'Alice' });Solution
Step 1: Understand the mock function
getUser returns a promise resolved with an object { id: 5, name: 'Alice' }.Step 2: Analyze the .then(console.log) call
The .then method receives the resolved value and logs it, so the output is the object itself.Final Answer:
{ id: 5, name: 'Alice' } -> Option AQuick Check:
Promise resolves to object logged [OK]
- Thinking console.log prints the promise object
- Expecting undefined because of missing await
- Assuming getUser is undefined or error
function fetchData() {
return new Promise(data => {
resolve({ id: 1, value: 'mock' });
});
}Solution
Step 1: Review Promise constructor usage
The Promise constructor expects an executor function with two parameters: resolve and reject.Step 2: Identify misuse of parameter
The code declares executor parameter as 'data' but calls resolve(...), where resolve is undefined. It should declare (resolve, reject) and call resolve(value).Final Answer:
The promise executor function parameter should be (resolve, reject), not (data) -> Option BQuick Check:
Promise executor = (resolve, reject) [OK]
- Using wrong parameter name in Promise executor
- Not returning a promise for async behavior
- Confusing async function with Promise constructor
Solution
Step 1: Understand requirement for success and failure
The mock must sometimes resolve with data and sometimes reject with an error to test both cases.Step 2: Analyze each option
const mockDb = () => Math.random() > 0.5 ? Promise.resolve({ id: 1 }) : Promise.reject(new Error('DB error')); returns a promise that resolves or rejects based on random chance, correctly simulating success or failure.
const mockDb = () => { if (Math.random() > 0.5) return { id: 1 }; else throw new Error('DB error'); }; throws error synchronously, not returning a promise rejection.
const mockDb = () => Promise.resolve({ id: 1 }); always resolves, no error simulation.
const mockDb = () => new Promise((resolve) => resolve({ id: 1 })); always resolves, no error simulation.Final Answer:
const mockDb = () => Math.random() > 0.5 ? Promise.resolve({ id: 1 }) : Promise.reject(new Error('DB error')); -> Option CQuick Check:
Random resolve or reject simulates success/error [OK]
- Throwing error instead of rejecting promise
- Always resolving without error case
- Not returning a promise for async simulation
Ready to prove it?
Pass the test and this pattern moves unknown
