0
0
Expressframework~30 mins

Mocking database calls in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Mocking database calls in Express
📖 Scenario: You are building a simple Express server that fetches user data from a database. To test your server without a real database, you will mock the database calls.
🎯 Goal: Create an Express server with a mocked database call that returns user data. You will set up the data, configure a mock function, implement the route using the mock, and complete the server setup.
📋 What You'll Learn
Create a mock user data array called users with exact user objects
Create a mock function called getUsersFromDb that returns the users array
Create an Express route /users that uses getUsersFromDb to send user data as JSON
Complete the Express server setup with app.listen on port 3000
💡 Why This Matters
🌍 Real World
Mocking database calls helps developers test server routes without needing a real database connection. This speeds up development and testing.
💼 Career
Backend developers often mock database calls to write unit tests and develop APIs before the database is ready or to isolate code during testing.
Progress0 / 4 steps
1
DATA SETUP: Create mock user data
Create a constant array called users with these exact objects: { id: 1, name: 'Alice' } and { id: 2, name: 'Bob' }.
Express
Need a hint?

Use const users = [ ... ] with two objects inside the array.

2
CONFIGURATION: Create mock database function
Create a function called getUsersFromDb that returns the users array.
Express
Need a hint?

Define a function named getUsersFromDb that returns the users array.

3
CORE LOGIC: Create Express route using mock function
Import Express, create an app with express(), and add a GET route /users that calls getUsersFromDb() and sends the result as JSON with res.json().
Express
Need a hint?

Use require('express') to import Express, create app, and define the GET route with app.get.

4
COMPLETION: Start the Express server
Add app.listen to start the server on port 3000.
Express
Need a hint?

Use app.listen(3000) to start the server on port 3000.