Bird
Raised Fist0
Expressframework~20 mins

Mocking database calls in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mocking Mastery in Express
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when mocking a database call with Jest in Express?
Consider this Express route handler that uses a mocked database call. What will be the response sent to the client?
Express
const express = require('express');
const app = express();

// Mock database module
const db = {
  getUser: jest.fn(() => Promise.resolve({ id: 1, name: 'Alice' }))
};

app.get('/user', async (req, res) => {
  const user = await db.getUser();
  res.json(user);
});

// Simulate a request to /user
(async () => {
  const req = { method: 'GET', url: '/user' };
  const res = { json: (data) => console.log(JSON.stringify(data)) };
  app.handle(req, res, () => {});
})();
ATypeError: db.getUser is not a function
Bundefined
C{"id":1,"name":"Alice"}
DSyntaxError
Attempts:
2 left
💡 Hint
Think about what the mocked function returns and how the route sends the response.
📝 Syntax
intermediate
2:00remaining
Which option correctly mocks a database call returning a rejected promise in Jest?
You want to mock a database call that fails with an error. Which code correctly mocks this behavior?
Express
const db = {
  getUser: jest.fn()
};

// Your mocking code here
Adb.getUser.mockResolvedValue(new Error('DB error'));
Bdb.getUser.mockRejectedValue('DB error');
Cdb.getUser.mockReturnValue(new Error('DB error'));
Ddb.getUser.mockReturnValue(Promise.reject(new Error('DB error')));
Attempts:
2 left
💡 Hint
Use the Jest method designed for rejected promises.
🔧 Debug
advanced
2:30remaining
Why does this mocked database call not update the state in Express?
Given this Express route and mock, why does the response always show the initial user name instead of the updated one?
Express
const db = {
  user: { id: 1, name: 'Alice' },
  getUser: jest.fn(() => Promise.resolve(db.user)),
  updateUser: jest.fn((newName) => { db.user.name = newName; return Promise.resolve(db.user); })
};

app.post('/user', async (req, res) => {
  await db.updateUser('Bob');
  const user = await db.getUser();
  res.json(user);
});
AThe mock functions share the same user object, so the update should reflect; no issue here.
BThe updateUser mock does not actually change the user object because of closure scope.
CThe getUser mock returns a new object copy, so changes to db.user are not seen.
DThe asynchronous calls are not awaited properly, causing stale data.
Attempts:
2 left
💡 Hint
Look at how the user object is shared between mocks.
❓ lifecycle
advanced
2:00remaining
What happens if you forget to reset mocks between tests in Express with Jest?
You have multiple tests mocking the same database call. What is the likely effect of not resetting mocks between tests?
AMocks retain call history and implementations, causing tests to interfere and produce false positives or negatives.
BMocks automatically reset after each test, so no effect occurs.
CTests will fail immediately with a Jest error about mock state.
DMocks become undefined and cause runtime errors.
Attempts:
2 left
💡 Hint
Think about how Jest tracks mock calls and implementations.
🧠 Conceptual
expert
1:30remaining
Which option best describes the benefit of mocking database calls in Express unit tests?
Why do developers mock database calls when testing Express route handlers?
ATo replace Express middleware with database logic for integration testing.
BTo ensure the database schema is tested thoroughly during route handler tests.
CTo increase test execution time by adding complexity with mocks.
DTo isolate route logic from database dependencies, making tests faster and more reliable by avoiding real database access.
Attempts:
2 left
💡 Hint
Think about what makes unit tests fast and stable.

Practice

(1/5)
1. What is the main purpose of mocking database calls in Express applications?
easy
A. To test code without needing a real database connection
B. To speed up the database queries in production
C. To permanently replace the database with fake data
D. To make the database store data faster

Solution

  1. Step 1: Understand mocking concept

    Mocking means creating fake versions of parts of your app, like database calls, to test without real dependencies.
  2. 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.
  3. Final Answer:

    To test code without needing a real database connection -> Option A
  4. Quick Check:

    Mocking = Test without real DB [OK]
Hint: Mocking means faking DB calls to test code fast [OK]
Common Mistakes:
  • Thinking mocking speeds up production DB
  • Confusing mocking with permanent DB replacement
  • Assuming mocking changes real data storage
2. Which of the following is the correct way to mock a database call returning a promise in Express?
easy
A. const mockDbCall = Promise.resolve({ id: 1, name: 'Test' });
B. const mockDbCall = () => { return { id: 1, name: 'Test' }; };
C. const mockDbCall = () => new Promise({ id: 1, name: 'Test' });
D. const mockDbCall = () => Promise.resolve({ id: 1, name: 'Test' });

Solution

  1. Step 1: Understand promise returning function

    A mock database call should return a promise that resolves to data, so Promise.resolve is correct.
  2. 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.
  3. Final Answer:

    const mockDbCall = () => Promise.resolve({ id: 1, name: 'Test' }); -> Option D
  4. Quick Check:

    Promise.resolve returns a resolved promise [OK]
Hint: Use Promise.resolve to return mock data as a promise [OK]
Common Mistakes:
  • Returning plain object instead of a promise
  • Using new Promise without executor function
  • Assigning a promise directly instead of a function returning it
3. Given the mock function below, what will getUser().then(console.log) output?
const getUser = () => Promise.resolve({ id: 5, name: 'Alice' });
medium
A. { id: 5, name: 'Alice' }
B. Promise { { id: 5, name: 'Alice' } }
C. undefined
D. Error: getUser is not a function

Solution

  1. Step 1: Understand the mock function

    getUser returns a promise resolved with an object { id: 5, name: 'Alice' }.
  2. 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.
  3. Final Answer:

    { id: 5, name: 'Alice' } -> Option A
  4. Quick Check:

    Promise resolves to object logged [OK]
Hint: Promise.then logs resolved value, not the promise itself [OK]
Common Mistakes:
  • Thinking console.log prints the promise object
  • Expecting undefined because of missing await
  • Assuming getUser is undefined or error
4. Identify the error in this mock database call function:
function fetchData() {
  return new Promise(data => {
    resolve({ id: 1, value: 'mock' });
  });
}
medium
A. The function should be async instead of returning a promise
B. The promise executor function parameter should be (resolve, reject), not (data)
C. The data object is missing a required field
D. The function should not return a promise

Solution

  1. Step 1: Review Promise constructor usage

    The Promise constructor expects an executor function with two parameters: resolve and reject.
  2. 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).
  3. Final Answer:

    The promise executor function parameter should be (resolve, reject), not (data) -> Option B
  4. Quick Check:

    Promise executor = (resolve, reject) [OK]
Hint: Promise executor needs (resolve, reject) parameters [OK]
Common Mistakes:
  • Using wrong parameter name in Promise executor
  • Not returning a promise for async behavior
  • Confusing async function with Promise constructor
5. You want to mock a database call in Express that sometimes returns data and sometimes throws an error to test error handling. Which mock function correctly simulates this behavior?
hard
A. const mockDb = () => Promise.resolve({ id: 1 });
B. const mockDb = () => { if (Math.random() > 0.5) return { id: 1 }; else throw new Error('DB error'); };
C. const mockDb = () => Math.random() > 0.5 ? Promise.resolve({ id: 1 }) : Promise.reject(new Error('DB error'));
D. const mockDb = () => new Promise((resolve) => resolve({ id: 1 }));

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    const mockDb = () => Math.random() > 0.5 ? Promise.resolve({ id: 1 }) : Promise.reject(new Error('DB error')); -> Option C
  4. Quick Check:

    Random resolve or reject simulates success/error [OK]
Hint: Use Promise.resolve or Promise.reject to simulate success or error [OK]
Common Mistakes:
  • Throwing error instead of rejecting promise
  • Always resolving without error case
  • Not returning a promise for async simulation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard