NestJS Technology & Digital Applications 3 — Questions and Answers
Question 1: In NestJS, which decorator registers a class as a middleware?
- @Middleware()
- @Injectable() combined with NestMiddleware interface (Correct answer)
- @UseMiddleware()
- @Module({ middleware })
Correct answer: @Injectable() combined with NestMiddleware interface
Middleware classes must be decorated with @Injectable() and implement the NestMiddleware interface which requires a use() method.
Question 2: What does the `forwardRef()` utility solve in NestJS?
- Lazy loading of feature modules
- Circular dependency issues between modules or providers (Correct answer)
- Forward-declaring controller routes
- Deferring provider instantiation
Correct answer: Circular dependency issues between modules or providers
forwardRef() resolves circular dependencies where two classes depend on each other by deferring reference resolution.
Question 3: Which decorator in NestJS is used to extract a specific property from a request object?
- @Query()
- @Param()
- @Body() (Correct answer)
- @Req()
Correct answer: @Body()
@Body() extracts the entire request body or a named property from it, while @Req() provides the full request object.
Question 4: In NestJS testing, what does `Test.createTestingModule()` return?
- A ready-to-use NestApplication instance
- A TestingModuleBuilder used to compile and create a testing module (Correct answer)
- A mock of the AppModule
- An HTTP test client
Correct answer: A TestingModuleBuilder used to compile and create a testing module
Test.createTestingModule() returns a TestingModuleBuilder, which you then call .compile() on to get the actual TestingModule.
Question 5: What is the function of `APP_GUARD` token in NestJS?
- Declares a guard that applies only to @Public() routes
- Registers a guard globally across all routes without @UseGuards() on every controller (Correct answer)
- Marks a guard as optional
- Assigns a guard to a specific module
Correct answer: Registers a guard globally across all routes without @UseGuards() on every controller
Providing a guard with the APP_GUARD token in any module registers it as a global guard applied to every route in the application.
Question 6: Which NestJS feature allows you to execute code when the application is shutting down?
- OnModuleDestroy lifecycle hook
- onApplicationShutdown lifecycle hook (Correct answer)
- OnApplicationClose interface
- CleanupModule
Correct answer: onApplicationShutdown lifecycle hook
The onApplicationShutdown() hook fires when the app receives a termination signal, allowing graceful cleanup before shutdown.
Question 7: When using NestJS with TypeORM, what decorator defines a class as a database entity?
- @Model()
- @Schema()
- @Entity() (Correct answer)
- @Table()
Correct answer: @Entity()
@Entity() from TypeORM marks a class as a database entity, mapping it to a corresponding database table.
In NestJS, which decorator registers a class as a middleware?