Bird
Raised Fist0
Expressframework~20 mins

Dependency injection in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Express Dependency Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the main benefit of using dependency injection in Express?

Why do developers use dependency injection in Express applications?

ATo tightly couple modules so they depend directly on each other
BTo make testing easier by allowing dependencies to be replaced or mocked
CTo increase the size of the application bundle for better performance
DTo avoid using middleware functions in the request pipeline
Attempts:
2 left
💡 Hint

Think about how you can swap parts of your app during tests.

❓ component_behavior
intermediate
2:00remaining
What will this Express middleware output when dependency injection is used correctly?

Consider this middleware that uses a service injected via req.services. What will it send as a response?

Express
app.use((req, res, next) => {
  const message = req.services.greetingService.getMessage();
  res.send(message);
});
A"Hello from the greeting service!"
B"Cannot read property 'getMessage' of undefined" error
C"undefined"
D"Hello World"
Attempts:
2 left
💡 Hint

Assume req.services.greetingService is properly injected and has a getMessage method returning a string.

📝 Syntax
advanced
2:00remaining
Which option correctly injects a service into Express request objects?

Choose the code snippet that properly adds a userService to each request using middleware.

A
app.use((req, res, next) => {
  req.userService = new UserService();
  next();
});
B
app.use((req, res, next) => {
  res.userService = new UserService();
  next();
});
C
app.use((req, res, next) => {
  next.userService = new UserService();
  next();
});
D
app.use((req, res, next) => {
  UserService = new UserService();
  next();
});
Attempts:
2 left
💡 Hint

Remember that req is the request object passed to handlers.

🔧 Debug
advanced
2:00remaining
Why does this injected service cause an error in Express?

Given this middleware, why does accessing req.services.dataService cause a TypeError?

Express
app.use((req, res, next) => {
  req.services.dataService = new DataService();
  next();
});

app.get('/', (req, res) => {
  res.send(req.services.dataService.getData());
});
A<code>next()</code> is not called in the middleware, blocking the request
B<code>DataService</code> is not defined anywhere in the code
CThe <code>getData()</code> method does not return a string
D<code>req.services</code> is undefined, so assigning <code>dataService</code> fails
Attempts:
2 left
💡 Hint

Check if req.services exists before assigning properties.

❓ state_output
expert
2:00remaining
What is the output of this Express app using dependency injection with a singleton service?

Consider this code where a singleton service counts requests. What will the response be after three requests?

Express
class CounterService {
  constructor() {
    this.count = 0;
  }
  increment() {
    this.count++;
    return this.count;
  }
}

const counterService = new CounterService();

app.use((req, res, next) => {
  req.counter = counterService;
  next();
});

app.get('/', (req, res) => {
  const currentCount = req.counter.increment();
  res.send(`Request number: ${currentCount}`);
});
ARequest number: 0
BRequest number: 1
CRequest number: 3
DRequest number: undefined
Attempts:
2 left
💡 Hint

Think about how the singleton service keeps state across requests.

Practice

(1/5)
1. What is the main purpose of dependency injection in an Express app?
easy
A. To provide parts of the app with the resources they need without hardcoding them
B. To make the app run faster by caching data
C. To automatically generate routes based on file names
D. To handle errors globally in the app

Solution

  1. Step 1: Understand dependency injection concept

    Dependency injection means giving parts of your app what they need instead of making them find it themselves.
  2. Step 2: Identify the purpose in Express

    In Express, this helps keep code organized and flexible by passing dependencies explicitly.
  3. Final Answer:

    To provide parts of the app with the resources they need without hardcoding them -> Option A
  4. Quick Check:

    Dependency injection = Provide needed resources [OK]
Hint: Think: "Give what is needed, don't make it find" [OK]
Common Mistakes:
  • Confusing dependency injection with caching
  • Thinking it auto-generates routes
  • Mixing it with error handling
2. Which of the following is the correct way to inject a service into an Express router?
easy
A. const router = express.Router(); router.use(service);
B. const router = express.Router(service);
C. function createRouter(service) { const router = express.Router(); router.service = service; return router; }
D. const router = express.Router(); router.service = service();

Solution

  1. Step 1: Check how to pass dependencies in Express

    Express.Router() does not accept parameters directly, so passing service as argument is invalid.
  2. Step 2: Use a factory function to inject service

    Creating a function that takes service and returns a router with service attached is the correct pattern.
  3. Final Answer:

    function createRouter(service) { const router = express.Router(); router.service = service; return router; } -> Option C
  4. Quick Check:

    Inject by factory function = function createRouter(service) { const router = express.Router(); router.service = service; return router; } [OK]
Hint: Use a function to pass dependencies, not Router constructor [OK]
Common Mistakes:
  • Passing service directly to express.Router()
  • Calling service as a middleware incorrectly
  • Assigning service without a factory function
3. Consider this code snippet:
function createService() {
  return { getName: () => 'MyService' };
}

function createRouter(service) {
  const router = require('express').Router();
  router.get('/name', (req, res) => {
    res.send(service.getName());
  });
  return router;
}

const service = createService();
const router = createRouter(service);

// What happens when a GET request is made to '/name'?
medium
A. The server will crash due to missing middleware
B. The response will be undefined
C. There will be a runtime error because service is not defined
D. The response will be 'MyService'

Solution

  1. Step 1: Analyze service creation

    The createService function returns an object with getName method returning 'MyService'.
  2. Step 2: Analyze router handler

    The router uses the injected service and calls getName to send the response on '/name' route.
  3. Final Answer:

    The response will be 'MyService' -> Option D
  4. Quick Check:

    Injected service method returns 'MyService' [OK]
Hint: Injected service methods run as expected in route handlers [OK]
Common Mistakes:
  • Assuming service is undefined inside handler
  • Thinking service causes runtime error
  • Confusing middleware with service injection
4. You have this code snippet:
function createRouter(service) {
  const router = require('express').Router();
  router.get('/data', (req, res) => {
    res.send(service.getData());
  });
  return router;
}

const router = createRouter();
What is the main issue here?
medium
A. The router is missing the service argument, causing service to be undefined
B. The router should be created with express() instead of express.Router()
C. The getData method is not defined on the router
D. The route path '/data' is invalid in Express

Solution

  1. Step 1: Check function call for createRouter

    The createRouter function expects a service argument, but none is passed, so service is undefined.
  2. Step 2: Understand impact on route handler

    Calling service.getData() will cause a runtime error because service is undefined.
  3. Final Answer:

    The router is missing the service argument, causing service to be undefined -> Option A
  4. Quick Check:

    Missing dependency argument = undefined service [OK]
Hint: Always pass dependencies when calling factory functions [OK]
Common Mistakes:
  • Thinking express() should replace express.Router() here
  • Confusing method definition with dependency injection
  • Assuming route path is invalid
5. You want to inject a database client into multiple routers in your Express app. Which approach best supports this using dependency injection?
hard
A. Use a global variable for the database client and import it in each router file
B. Create a factory function for each router that accepts the database client and returns a configured router
C. Attach the database client directly to the Express app instance and access it via req.app
D. Create middleware that initializes the database client on every request

Solution

  1. Step 1: Understand dependency injection best practice

    Injecting dependencies via factory functions keeps routers independent and testable.
  2. Step 2: Evaluate options for injecting database client

    Factory functions allow passing the client explicitly to each router, avoiding globals and repeated initialization.
  3. Final Answer:

    Create a factory function for each router that accepts the database client and returns a configured router -> Option B
  4. Quick Check:

    Factory functions for injection = Create a factory function for each router that accepts the database client and returns a configured router [OK]
Hint: Use factory functions to pass shared resources cleanly [OK]
Common Mistakes:
  • Using global variables which reduce testability
  • Attaching client to app instance instead of injecting
  • Initializing client on every request causing overhead
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