Mocking database calls lets you test your code without needing a real database. It helps you check if your app works correctly and faster.
Mocking database calls in 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.
const mockDb = {
findUserById: (id) => Promise.resolve({ id, name: 'Bob' })
};const mockDb = {
getAllUsers: () => Promise.resolve([]) // returns empty list
};const mockDb = {
getUser: () => Promise.reject(new Error('DB error'))
};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.
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'); });
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.
Mocking helps test code without a real database.
Use simple functions returning promises to simulate database calls.
Mocks improve development speed and test reliability.
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
