0
0
NestJSframework~20 mins

Event handling in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 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.