Bird
Raised Fist0
NestJSframework~20 mins

Event handling in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Event Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an event is emitted in NestJS?

Consider a NestJS application where an event is emitted using this.eventEmitter.emit('user.created', user). What is the expected behavior if there is a listener subscribed to the 'user.created' event?

NestJS
import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class UserService {
  constructor(private eventEmitter: EventEmitter2) {}

  createUser(user) {
    // user creation logic
    this.eventEmitter.emit('user.created', user);
  }
}

// Listener example
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class UserListener {
  @OnEvent('user.created')
  handleUserCreatedEvent(payload) {
    console.log('User created:', payload);
  }
}
AThe eventEmitter throws an error if no listener is found for the event.
BThe event is queued and processed only after the application restarts.
CThe listener method handleUserCreatedEvent is called with the user object as payload.
DThe event is ignored if no listener is registered at the time of emission.
Attempts:
2 left
💡 Hint

Think about how event emitters work in NestJS and whether events are synchronous or asynchronous.

📝 Syntax
intermediate
2:00remaining
Identify the correct syntax to listen for an event in NestJS

Which of the following code snippets correctly listens to an event named 'order.completed' using NestJS event emitter?

A
@ListenEvent('order.completed')
handleOrderCompleted(payload) {
  console.log(payload);
}
B
@EventListener('order.completed')
handleOrderCompleted(payload) {
  console.log(payload);
}
C
this.eventEmitter.on('order.completed', (payload) => {
  console.log(payload);
});
D
@OnEvent('order.completed')
handleOrderCompleted(payload) {
  console.log(payload);
}
Attempts:
2 left
💡 Hint

Recall the decorator provided by NestJS for event listening.

🔧 Debug
advanced
2:30remaining
Why does the event listener not respond to emitted events?

Given the following NestJS code, why does the listener not log anything when createUser is called?

import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class UserService {
  constructor(private eventEmitter: EventEmitter2) {}

  createUser(user) {
    this.eventEmitter.emit('user.created', user);
  }
}

@Injectable()
export class UserListener {
  @OnEvent('user.created')
  handleUserCreated(payload) {
    console.log('User created:', payload);
  }
}
AThe event name 'user.created' is misspelled in the emit call.
BThe UserListener class is not instantiated because it is not injected anywhere, so its listener method never runs.
CThe EventEmitter2 instance is not properly injected into UserListener.
DThe listener method handleUserCreated is missing the async keyword.
Attempts:
2 left
💡 Hint

Think about how NestJS creates instances of classes and when decorators like @OnEvent are activated.

❓ state_output
advanced
2:00remaining
What is the output when multiple listeners handle the same event?

Consider two listeners subscribed to the 'task.finished' event. When the event is emitted with payload { id: 42 }, what will be the console output?

import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class ListenerOne {
  @OnEvent('task.finished')
  handleTask(payload) {
    console.log('ListenerOne:', payload.id);
  }
}

@Injectable()
export class ListenerTwo {
  @OnEvent('task.finished')
  handleTask(payload) {
    console.log('ListenerTwo:', payload.id);
  }
}

// Emitting event
this.eventEmitter.emit('task.finished', { id: 42 });
A
ListenerOne: 42
ListenerTwo: 42
BListenerOne: 42
CListenerTwo: 42
DNo output because multiple listeners cause a conflict.
Attempts:
2 left
💡 Hint

Think about how event emitters handle multiple listeners for the same event.

🧠 Conceptual
expert
2:30remaining
What error occurs if EventEmitter2 is not provided in a NestJS module?

In a NestJS module, if you try to inject EventEmitter2 without importing EventEmitterModule, what error will you encounter at runtime?

ANest can't resolve dependencies of the class: No provider for EventEmitter2!
BTypeError: eventEmitter.emit is not a function
CSyntaxError: Unexpected token in event emitter import
DRuntimeError: EventEmitter2 module not found
Attempts:
2 left
💡 Hint

Think about how NestJS dependency injection works and what happens if a provider is missing.

Practice

(1/5)
1. What is the main purpose of event handling in a NestJS application?
easy
A. To allow different parts of the app to react to actions without being tightly connected
B. To directly call methods from other classes
C. To replace all HTTP requests with events
D. To store data permanently in the database

Solution

  1. Step 1: Understand event handling concept

    Event handling lets parts of an app respond to actions independently, avoiding tight coupling.
  2. Step 2: Compare options

    Only To allow different parts of the app to react to actions without being tightly connected describes this purpose correctly; others describe unrelated concepts.
  3. Final Answer:

    To allow different parts of the app to react to actions without being tightly connected -> Option A
  4. Quick Check:

    Event handling = loose coupling reaction [OK]
Hint: Event handling means reacting without tight connections [OK]
Common Mistakes:
  • Thinking event handling replaces HTTP requests
  • Confusing event handling with direct method calls
  • Assuming event handling stores data
2. Which decorator is used to mark a class as an event handler in NestJS?
easy
A. @HandleEvent
B. @EventListener
C. @EventsHandler
D. @EventSubscriber

Solution

  1. Step 1: Recall NestJS event handler syntax

    The correct decorator to mark event handler classes is @EventsHandler.
  2. Step 2: Verify options

    Options B, C, and D are not valid NestJS decorators for event handlers.
  3. Final Answer:

    @EventsHandler -> Option C
  4. Quick Check:

    @EventsHandler marks event handlers [OK]
Hint: Use @EventsHandler to mark event handler classes [OK]
Common Mistakes:
  • Using @EventListener which is not a NestJS decorator
  • Confusing with @HandleEvent which does not exist
  • Using @EventSubscriber which is from other frameworks
3. Given this event handler code, what will be logged when eventBus.publish(new UserCreatedEvent('Alice')) is called?
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';

export class UserCreatedEvent {
  constructor(public readonly username: string) {}
}

@EventsHandler(UserCreatedEvent)
export class UserCreatedHandler implements IEventHandler<UserCreatedEvent> {
  handle(event: UserCreatedEvent) {
    console.log(`User created: ${event.username}`);
  }
}
medium
A. User created: undefined
B. No output because eventBus.publish does nothing
C. Error: handle method missing
D. User created: Alice

Solution

  1. Step 1: Understand event publishing and handling

    Publishing UserCreatedEvent triggers UserCreatedHandler which logs the username.
  2. Step 2: Check the handle method output

    The handle method logs "User created: " plus the event's username, which is "Alice".
  3. Final Answer:

    User created: Alice -> Option D
  4. Quick Check:

    Event publish triggers handler log [OK]
Hint: Publishing event triggers handle() logging username [OK]
Common Mistakes:
  • Assuming username is undefined
  • Thinking handle method is missing
  • Believing eventBus.publish does nothing
4. What is wrong with this event handler code?
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';

export class OrderPlacedEvent {
  constructor(public readonly orderId: number) {}
}

@EventsHandler(OrderPlacedEvent)
export class OrderPlacedHandler implements IEventHandler<OrderPlacedEvent> {
  handle() {
    console.log('Order placed:', orderId);
  }
}
medium
A. The handle method is missing the event parameter
B. The @EventsHandler decorator is used incorrectly
C. The event class should not have a constructor
D. The console.log syntax is invalid

Solution

  1. Step 1: Check handle method signature

    The handle method must accept the event parameter to access event data.
  2. Step 2: Identify usage of event data

    Inside handle, orderId is used but not defined because event parameter is missing.
  3. Final Answer:

    The handle method is missing the event parameter -> Option A
  4. Quick Check:

    handle(event) needs event parameter [OK]
Hint: handle() must receive event parameter to access data [OK]
Common Mistakes:
  • Omitting event parameter in handle method
  • Misusing @EventsHandler decorator
  • Thinking constructor is not needed in event class
5. You want to handle two different events, UserCreatedEvent and UserDeletedEvent, in one handler class. Which approach correctly implements this in NestJS?
hard
A. Use @EventsHandler without parameters and check event type inside handle method
B. Use @EventsHandler(UserCreatedEvent, UserDeletedEvent) on one class and implement handle(event) with type checks
C. Use @EventsHandler on one class but implement two separate handle methods named handleUserCreated and handleUserDeleted
D. Create two separate handler classes each with @EventsHandler for one event

Solution

  1. Step 1: Understand multiple event handling in one class

    In NestJS, you can pass multiple event classes to @EventsHandler decorator on one class.
  2. Step 2: Implement single handle method with event type checks

    The handle method receives any event instance; inside it, you check the event type to handle accordingly.
  3. Final Answer:

    Use @EventsHandler(UserCreatedEvent, UserDeletedEvent) on one class and implement handle(event) with type checks -> Option B
  4. Quick Check:

    Multiple events in one handler use @EventsHandler(...events) [OK]
Hint: Use @EventsHandler with multiple events and one handle method [OK]
Common Mistakes:
  • Trying to define multiple handle methods in one class
  • Creating separate classes instead of one combined handler
  • Using @EventsHandler without parameters
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