Bird
Raised Fist0
NestJSframework~20 mins

Constructor injection in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Constructor Injection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS service using constructor injection?

Consider this NestJS service that injects a repository via constructor injection. What will be logged when getData() is called?

NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class DataService {
  constructor(private readonly repo: { find: () => string }) {}

  getData() {
    return this.repo.find();
  }
}

const fakeRepo = { find: () => 'data found' };
const service = new DataService(fakeRepo);
console.log(service.getData());
ASyntaxError
B"undefined"
C"data found"
DTypeError: this.repo.find is not a function
Attempts:
2 left
💡 Hint

Constructor injection assigns the passed object to the private readonly property repo.

📝 Syntax
intermediate
2:00remaining
Which option correctly injects a service using NestJS constructor injection?

Choose the correct syntax for injecting MyService into AppService using constructor injection.

Aconstructor(private readonly myService: MyService) {}
Bconstructor(private myService: MyService) {}
Cconstructor(myService: MyService) { this.myService = myService; }
Dconstructor(public myService: MyService) {}
Attempts:
2 left
💡 Hint

Use private readonly to declare and assign the injected service in one step.

🔧 Debug
advanced
2:00remaining
Why does this NestJS service throw an error when using constructor injection?

Given this service, why does NestJS throw a runtime error about missing dependencies?

NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {
  constructor(private readonly repo) {}

  getUser() {
    return this.repo.findUser();
  }
}
AThe constructor parameter lacks a type, so NestJS cannot resolve the dependency.
BThe repo property should be public, not private readonly.
CThe @Injectable decorator is missing from the repo class.
DThe getUser method must be async to use the repo.
Attempts:
2 left
💡 Hint

Check if NestJS can identify the dependency type from the constructor.

❓ state_output
advanced
2:00remaining
What is the value of the injected service property after instantiation?

In this NestJS controller, what will be the value of this.authService.isLoggedIn after the constructor runs?

NestJS
import { Controller } from '@nestjs/common';

class AuthService {
  isLoggedIn = false;
}

@Controller()
export class AuthController {
  constructor(private readonly authService: AuthService) {
    this.authService.isLoggedIn = true;
  }
}
Aundefined
Bfalse
CThrows ReferenceError
Dtrue
Attempts:
2 left
💡 Hint

The constructor sets isLoggedIn to true explicitly.

🧠 Conceptual
expert
2:00remaining
Which statement best describes constructor injection in NestJS?

Choose the most accurate description of how constructor injection works in NestJS.

AConstructor injection requires manually creating instances and passing them to the constructor when creating a class.
BNestJS uses the constructor parameter types to automatically resolve and inject dependencies registered in its module system.
CDependencies must be injected via setter methods after the class is instantiated.
DNestJS only supports property injection, not constructor injection.
Attempts:
2 left
💡 Hint

Think about how NestJS uses TypeScript metadata to inject services.

Practice

(1/5)
1. What is the main purpose of constructor injection in NestJS?
easy
A. To provide required services to a class when it is created
B. To manually create instances of services inside methods
C. To define routes for HTTP requests
D. To write database queries inside the constructor

Solution

  1. Step 1: Understand constructor injection concept

    Constructor injection is used to pass dependencies (services) into a class automatically when it is created.
  2. Step 2: Identify the purpose in NestJS context

    In NestJS, constructor injection helps keep code clean by providing needed services without manual instantiation.
  3. Final Answer:

    To provide required services to a class when it is created -> Option A
  4. Quick Check:

    Constructor injection = provide services automatically [OK]
Hint: Constructor injection means passing services via constructor [OK]
Common Mistakes:
  • Thinking constructor injection creates routes
  • Manually creating service instances inside methods
  • Confusing injection with database queries
2. Which of the following is the correct syntax for constructor injection of a service named UsersService in a NestJS class?
easy
A. constructor(private readonly usersService: UsersService) {}
B. constructor(usersService: UsersService) {}
C. constructor(private usersService) {}
D. constructor(public readonly usersService) {}

Solution

  1. Step 1: Check for correct access modifier and typing

    In NestJS, constructor injection requires private readonly with the service type for proper injection and immutability.
  2. Step 2: Compare options

    constructor(private readonly usersService: UsersService) {} (A) is correct. B misses access modifier, C misses type, D misses type annotation.
  3. Final Answer:

    constructor(private readonly usersService: UsersService) {} -> Option A
  4. Quick Check:

    Use private readonly with type for injection [OK]
Hint: Use 'private readonly serviceName: ServiceType' in constructor [OK]
Common Mistakes:
  • Omitting access modifier like private or public
  • Not specifying the service type
  • Using public readonly without specifying the service type
3. Given the following code, what will be the output when appController.getHello() is called?
import { Injectable, Controller } from '@nestjs/common';

@Injectable()
class HelloService {
  getMessage() {
    return 'Hello, NestJS!';
  }
}

@Controller()
class AppController {
  constructor(private readonly helloService: HelloService) {}

  getHello() {
    return this.helloService.getMessage();
  }
}
medium
A. Error: helloService is not defined
B. undefined
C. 'Hello, NestJS!'
D. 'Hello, World!'

Solution

  1. Step 1: Understand constructor injection usage

    The AppController receives HelloService via constructor injection and stores it as helloService.
  2. Step 2: Trace method call

    Calling getHello() calls helloService.getMessage() which returns 'Hello, NestJS!'.
  3. Final Answer:

    'Hello, NestJS!' -> Option C
  4. Quick Check:

    Injected service method returns 'Hello, NestJS!' [OK]
Hint: Injected service methods return expected values [OK]
Common Mistakes:
  • Assuming service is undefined without injection
  • Confusing method return values
  • Expecting default or unrelated strings
4. Identify the error in the following NestJS service injection code:
@Injectable()
class CatsService {}

@Controller('cats')
class CatsController {
  constructor(catsService: CatsService) {}

  findAll() {
    return 'All cats';
  }
}
medium
A. CatsService is not decorated with @Injectable()
B. Missing access modifier (private/public) in constructor parameter
C. Controller decorator is missing path
D. findAll method should be async

Solution

  1. Step 1: Check constructor injection syntax

    The constructor parameter catsService: CatsService lacks an access modifier like private or public, so it won't be assigned as a class property.
  2. Step 2: Verify other parts

    @Injectable() is present on service, @Controller('cats') has path, and findAll can be sync. So no other errors.
  3. Final Answer:

    Missing access modifier (private/public) in constructor parameter -> Option B
  4. Quick Check:

    Constructor injection needs access modifier [OK]
Hint: Always add private/public to constructor params for injection [OK]
Common Mistakes:
  • Omitting private/public in constructor injection
  • Thinking @Injectable is missing when it is present
  • Assuming controller path is mandatory for injection
5. You want to inject two services, AuthService and UsersService, into a NestJS controller. Which constructor correctly injects both services following best practices?
hard
A. constructor(public authService: AuthService, public usersService: UsersService) {}
B. constructor(authService: AuthService, usersService: UsersService) {}
C. constructor(private authService: AuthService, usersService: UsersService) {}
D. constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {}

Solution

  1. Step 1: Check for access modifiers and readonly usage

    Best practice is to use private readonly for injected services to keep them immutable and private.
  2. Step 2: Verify both services are injected with correct syntax

    constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {} injects both services with private readonly, while others miss modifiers or use public.
  3. Final Answer:

    constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {} -> Option D
  4. Quick Check:

    Use private readonly for multiple injected services [OK]
Hint: Use private readonly for all injected services in constructor [OK]
Common Mistakes:
  • Omitting access modifiers on one or both services
  • Using public instead of private readonly
  • Mixing access modifiers inconsistently
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