NestJS Developer Skills Assessment — Questions and Answers
Question 1: What is the framework entirely in?
- Angular
- HTML
- React
- TypeScript (Correct answer)
Correct answer: TypeScript
NestJS is built entirely with and heavily leverages TypeScript. This choice provides strong typing, which enhances code quality, maintainability, and developer tooling, especially for large-scale applications. TypeScript's features are integral to NestJS's architecture, enabling a more robust and predictable development experience.
Question 2: How do you inject Prisma Client as a service in NestJS?
- Prisma auto-registers with NestJS when installed
- Import PrismaModule.forRoot() and use @Prisma() decorator
- Use @InjectPrisma() decorator from @nestjs/prisma
- Create a PrismaService that extends PrismaClient, mark it @Injectable(), and inject it by class type (Correct answer)
Correct answer: Create a PrismaService that extends PrismaClient, mark it @Injectable(), and inject it by class type
The idiomatic pattern is creating a PrismaService extending PrismaClient, decorating it with @Injectable(), and providing it in AppModule so it can be injected anywhere.
Question 3: What does the `exports` array in @Module() control?
- Which controllers are public
- The order of middleware execution
- Which guards are applied globally
- Which providers can be used by other modules (Correct answer)
Correct answer: Which providers can be used by other modules
The `exports` array specifies which providers from the current module are available for other modules that import it.
Question 4: What is the purpose of regular risk reviews in NestJS practice?
- To generate reports
- To identify new risks, evaluate control effectiveness, and update mitigation strategies (Correct answer)
- To satisfy auditors only
- To reduce workload
Correct answer: To identify new risks, evaluate control effectiveness, and update mitigation strategies
This is fundamental to NestJS practice. To identify new risks, evaluate control effectiveness, and update mitigation strategies represents the professional standard for risk management in the NestJS certification framework.
Question 5: How do NestJS professionals contribute to advancing their field?
- By competing with colleagues
- By conducting research, sharing outcomes, mentoring others, and participating in professional forums (Correct answer)
- Individual contribution is not possible
- By maintaining current practices
Correct answer: By conducting research, sharing outcomes, mentoring others, and participating in professional forums
This is fundamental to NestJS practice. By conducting research, sharing outcomes, mentoring others, and participating in professional forums represents the professional standard for research in the NestJS certification framework.
Question 6: Which SOLID principle is most directly enforced by NestJS's dependency injection system?
- Open/Closed
- Single Responsibility
- Interface Segregation
- Dependency Inversion (Correct answer)
Correct answer: Dependency Inversion
NestJS DI enforces the Dependency Inversion Principle by having high-level modules depend on abstractions (tokens/interfaces) rather than concrete implementations.
Question 7: How do you handle database seeding in a NestJS TypeORM project?
- Use TypeOrmModule's built-in seed option
- Seeds run automatically from the entities/seeds folder
- Use @Seed() decorator on a provider method
- Create a seed script that uses DataSource directly and run it via a npm script (Correct answer)
Correct answer: Create a seed script that uses DataSource directly and run it via a npm script
Database seeding in TypeORM is typically done via a standalone TypeScript script that initializes DataSource and uses repositories to insert data, run manually or in CI.
Question 8: A NestJS service makes external HTTP calls. What professional pattern prevents cascading failures when the downstream service is slow?
- Cache the last successful response permanently
- Implement a circuit breaker pattern with timeout and fallback using a library like Cockatiel or Nest's HttpModule with timeout (Correct answer)
- Increase server timeout to 5 minutes to ensure completion
- Retry the request indefinitely until it succeeds
Correct answer: Implement a circuit breaker pattern with timeout and fallback using a library like Cockatiel or Nest's HttpModule with timeout
Circuit breakers halt calls to failing services and return fallbacks, preventing slow dependencies from exhausting the calling service's resources.
Question 9: Which NestJS architectural concept is analogous to Angular's NgModule?
- Controller
- Provider
- Module (Correct answer)
- Guard
Correct answer: Module
NestJS Module (decorated with @Module()) mirrors Angular's NgModule concept, serving as a cohesive block of related functionality.
Question 10: What is the purpose of TypeORM migrations in a NestJS production application?
- To back up the database before schema changes
- To seed the database with test data
- To synchronize entity definitions automatically on startup
- To safely evolve the database schema in a controlled, versioned manner (Correct answer)
Correct answer: To safely evolve the database schema in a controlled, versioned manner
Migrations provide versioned, reversible SQL scripts that alter the database schema without losing data — essential in production where `synchronize: true` is dangerous.
Question 11: What is the value of written documentation in NestJS professional communication?
- It is only for formal occasions
- It replaces verbal communication
- It creates permanent records, ensures clarity, and provides legal protection (Correct answer)
- It is optional
Correct answer: It creates permanent records, ensures clarity, and provides legal protection
This is fundamental to NestJS practice. It creates permanent records, ensures clarity, and provides legal protection represents the professional standard for communication in the NestJS certification framework.
Question 12: What is the purpose of the `providers` array in the @Module() decorator?
- To declare HTTP controllers
- To register services that can be injected within the module (Correct answer)
- To export public APIs
- To list imported modules
Correct answer: To register services that can be injected within the module
The `providers` array registers services (and other injectables) with the NestJS IoC container so they can be injected within that module.
Question 13: Which class do NestJS guards need to implement?
- CanActivate (Correct answer)
- HttpGuard
- RequestFilter
- GuardInterface
Correct answer: CanActivate
Guards must implement the CanActivate interface, which requires a canActivate() method that returns a boolean or Observable<boolean>.
Question 14: A team wants to broadcast notifications to all connected WebSocket clients in NestJS. Which method is typically used?
- this.server.emit() (Correct answer)
- this.eventEmitter.emit()
- this.client.send()
- this.gateway.broadcast()
Correct answer: this.server.emit()
In a NestJS WebSocket gateway, this.server.emit() broadcasts a message to every connected socket client.
Question 15: Which NestJS decorator is used to define a class as a module?
- @Injectable()
- @Component()
- @Module() (Correct answer)
- @Controller()
Correct answer: @Module()
The @Module() decorator marks a class as a NestJS module that organizes related providers, controllers, and imports.
Question 16: Which pattern does NestJS primarily use for organizing application logic?
- Microkernel
- MVC
- Modular architecture with DI (Correct answer)
- MVVM
Correct answer: Modular architecture with DI
NestJS uses a modular architecture combined with dependency injection (DI) to organize and decouple application components.
Question 17: A project manager requires all inter-service messages to carry a correlation ID for tracing. Where is the best place to inject this in NestJS?
- In the database entity
- In the Swagger decorator
- Inside each service method manually
- In a global interceptor that wraps every outgoing request (Correct answer)
Correct answer: In a global interceptor that wraps every outgoing request
A global interceptor can attach a correlation ID to every outgoing context before the handler executes.
Question 18: How do you configure TypeORM for asynchronous configuration (e.g., from ConfigService) in NestJS?
- TypeOrmModule.forRoot() with a factory
- DatabaseModule.withConfig() factory
- TypeOrmModule.forRootAsync() with useFactory (Correct answer)
- TypeOrmModule.configure() with async option
Correct answer: TypeOrmModule.forRootAsync() with useFactory
TypeOrmModule.forRootAsync() accepts a useFactory (or useClass/useExisting) that can inject ConfigService and return the database options asynchronously.
Question 19: How do you inject a TypeORM repository into a NestJS service?
- @Repository(User) private repo
- @TypeOrm(User) private repo: Repository<User>
- @Inject(Repository<User>) private repo: Repository<User>
- @InjectRepository(User) private repo: Repository<User> (Correct answer)
Correct answer: @InjectRepository(User) private repo: Repository<User>
@InjectRepository(Entity) is the TypeORM-specific injection decorator that retrieves the entity's repository from the DI container.
Question 20: Which NestJS built-in pipe should be used to prevent oversized request payloads?
- ValidationPipe with `maxBodySize`
- The `rawBody` limit in NestFactory options (Correct answer)
- MaxBodySizePipe
- ParseFilePipe with size validator
Correct answer: The `rawBody` limit in NestFactory options
Request body size limits are configured at the HTTP adapter level via NestFactory options (e.g., `bodyParser` limit), not through a NestJS pipe.
Question 21: What is the role of the `AppModule` in a NestJS application?
- It manages database connections
- It defines global guards
- It handles HTTP requests directly
- It serves as the root module that bootstraps the entire application (Correct answer)
Correct answer: It serves as the root module that bootstraps the entire application
AppModule is the root module passed to NestFactory.create(), which NestJS uses as the starting point to build the dependency graph.
Question 22: In NestJS, what is the primary security risk addressed by applying the @UseGuards(AuthGuard('jwt')) decorator to a controller?
- SQL injection in query parameters
- Memory leaks from unresolved promises
- CORS policy violations
- Unauthorized access by unauthenticated users (Correct answer)
Correct answer: Unauthorized access by unauthenticated users
AuthGuard enforces JWT verification before the route handler executes, blocking requests from unauthenticated callers.
Question 23: How do you create a circular dependency between two NestJS providers without causing errors?
- Use forwardRef() in both @Inject() decorators (Correct answer)
- Use a shared Global module
- Circular dependencies are impossible in NestJS
- Use @Inject() with lazy references
Correct answer: Use forwardRef() in both @Inject() decorators
forwardRef() wraps the class reference to defer its resolution, allowing NestJS to break the circular dependency loop during instantiation.
Question 24: A NestJS application processes file uploads. What risk is introduced if uploaded file types and sizes are not validated?
- Multer middleware silently rejects all files
- CORS preflight requests are blocked
- TypeScript decorators fail to compile
- Attackers can upload malicious executables or exhaust disk/memory with oversized files (Correct answer)
Correct answer: Attackers can upload malicious executables or exhaust disk/memory with oversized files
Without file-type and size checks, attackers can upload malware or trigger denial-of-service by sending excessively large files.
Question 25: What is a Lazy-loaded module in NestJS and when should it be used?
- A module that defers DI resolution until first use
- A module whose providers are destroyed after each request
- A module loaded on-demand to reduce initial startup time in serverless environments (Correct answer)
- A module loaded from a CDN at runtime
Correct answer: A module loaded on-demand to reduce initial startup time in serverless environments
Lazy-loaded modules are instantiated only when first requested, which reduces cold-start time — especially beneficial in serverless (Lambda) deployments.
Question 26: In NestJS, what is the risk of storing JWT refresh tokens only in memory on the server side?
- They are lost on process restart and cannot be revoked across instances (Correct answer)
- Memory storage is slower than database storage for token lookups
- NestJS Passport strategies do not support in-memory token stores
- They are automatically shared between microservice nodes
Correct answer: They are lost on process restart and cannot be revoked across instances
In-memory storage is ephemeral and node-local, making token revocation impossible in multi-instance deployments and causing session loss on restart.
Question 27: Which method in a TypeORM QueryBuilder is used to add a WHERE clause with a named parameter?
- .condition('field', 'value')
- .addFilter('field = ?', [value])
- .filter('condition', params)
- .where('entity.field = :value', { value }) (Correct answer)
Correct answer: .where('entity.field = :value', { value })
.where() (or .andWhere()) accepts a string condition with named `:param` placeholders and a params object to safely parameterize queries.
Question 28: How do you inject a non-class provider (e.g., a string token) in NestJS?
- @Value(TOKEN) decorator
- Automatic injection by type
- @Inject(TOKEN) in the constructor parameter (Correct answer)
- @InjectToken(TOKEN) decorator
Correct answer: @Inject(TOKEN) in the constructor parameter
@Inject(TOKEN) explicitly specifies the injection token to use when NestJS cannot infer it from the TypeScript type.
Question 29: Which file is the entry point of a NestJS application?
- app.controller.ts
- app.service.ts
- app.module.ts
- main.ts (Correct answer)
Correct answer: main.ts
main.ts bootstraps the NestJS application using NestFactory.create().
Question 30: Which NestJS concept allows a module to be shared across the entire application without re-importing?
- Feature Module
- Global Module (Correct answer)
- Dynamic Module
- Core Module
Correct answer: Global Module
A Global Module decorated with @Global() makes its exported providers available everywhere without requiring explicit imports.
Question 31: What does `TypeOrmModule.forFeature([Entity])` do in a feature module?
- Creates the database table for the entity
- Registers the entity's repository so it can be injected in that module (Correct answer)
- Runs migrations for the specified entity
- Exports the entity to other modules
Correct answer: Registers the entity's repository so it can be injected in that module
forFeature() registers the specified entities and makes their TypeORM repositories available for injection via @InjectRepository() within that module.
Question 32: Which decorator transforms a plain class into a NestJS injectable service?
- @Singleton()
- @Provider()
- @Service()
- @Injectable() (Correct answer)
Correct answer: @Injectable()
@Injectable() marks a class as a provider that the NestJS IoC container can instantiate and inject into other classes.
Question 33: What is the purpose of the `mockReturnValue()` method on a Jest mock function in NestJS tests?
- It resets the mock's call history and sets a new implementation
- It runs the real implementation once and then returns undefined
- It asserts the mock was called with the specified value
- It sets the value the mock function will return on every subsequent call (Correct answer)
Correct answer: It sets the value the mock function will return on every subsequent call
`mockReturnValue(val)` configures a `jest.fn()` mock to return `val` synchronously on every call, allowing you to control dependent service behavior in tests.
Question 34: Which NestJS configuration practice directly supports NIST SP 800-53 SC-28 (Protection of Information at Rest)?
- Using ConfigModule with environment variables for database URLs
- Enabling CORS with specific origins
- Encrypting the database volume and NestJS config secrets using a KMS (Correct answer)
- Using class-validator to validate DTOs
Correct answer: Encrypting the database volume and NestJS config secrets using a KMS
SC-28 requires encrypting sensitive data at rest; using a KMS for both the storage layer and application secrets satisfies this control.
Question 35: What framework help JS developers manage code more efficiently?
- React
- Vue
- Angular (Correct answer)
- None of the above
Correct answer: Angular
Angular is a comprehensive front-end framework that provides a highly structured and opinionated approach to building complex web applications. Its component-based architecture, strong typing with TypeScript, and extensive tooling help JavaScript developers manage large codebases more efficiently. This structured environment promotes maintainability and scalability, making code management easier.
Question 36: Which provider option allows asynchronous initialization, such as reading from a database?
- useClass
- useFactory with async function (Correct answer)
- useExisting
- useValue
Correct answer: useFactory with async function
`useFactory` accepts an async function, so NestJS will await the resolved value before making the provider available for injection.
Question 37: When analyzing NestJS OpenAPI documentation practices, which decorator applied to a DTO property describes it in the generated Swagger UI?
- @ApiProperty() (Correct answer)
- @ApiBody()
- @ApiResponse()
- @ApiParam()
Correct answer: @ApiProperty()
@ApiProperty() from @nestjs/swagger annotates DTO class properties so they appear with correct type information in Swagger UI.
Question 38: What is the purpose of `onModuleInit()` in a NestJS PrismaService?
- To seed the database with initial data
- To run database migrations on startup
- To validate the Prisma schema before startup
- To call this.$connect() and establish the database connection when the module loads (Correct answer)
Correct answer: To call this.$connect() and establish the database connection when the module loads
Implementing OnModuleInit and calling this.$connect() in onModuleInit() ensures Prisma establishes a connection when the NestJS module initializes.
Question 39: Based on NestJS documentation research, which approach allows a custom decorator to access route handler metadata set with @SetMetadata()?
- Using Reflector.get() inside a guard or interceptor (Correct answer)
- Using ConfigService inside the decorator
- Using the @Inject() decorator with a metadata token
- Using ExecutionContext.getArgs() directly
Correct answer: Using Reflector.get() inside a guard or interceptor
Reflector.get(metadataKey, handler) retrieves custom metadata set on a route with @SetMetadata(), typically used inside guards to implement role-based access.
Question 40: What is the purpose of the `useValue` option in a custom provider definition?
- To inject a factory function
- To provide a static value or mock object as a provider (Correct answer)
- To alias an existing provider
- To define an async provider
Correct answer: To provide a static value or mock object as a provider
`useValue` registers a static value (such as a config object or mock) directly as a provider without instantiation.
Question 41: How can you implement refresh token rotation in NestJS?
- Use @nestjs/passport's built-in token rotation feature
- Set a short JWT expiry and rely on automatic re-authentication
- Configure JwtModule with `rotate: true` option
- Store refresh tokens in the database, validate on use, then issue a new pair and invalidate the old token (Correct answer)
Correct answer: Store refresh tokens in the database, validate on use, then issue a new pair and invalidate the old token
Refresh token rotation requires persisting tokens in a DB, verifying the incoming token, issuing a new access+refresh pair, and invalidating the used refresh token to prevent reuse.
Question 42: Which NestJS package provides first-class TypeORM integration?
- @nestjs/typeorm (Correct answer)
- @nestjs/entity
- @nestjs/database
- @nestjs/orm
Correct answer: @nestjs/typeorm
@nestjs/typeorm provides TypeOrmModule with forRoot() and forFeature() methods for integrating TypeORM into the NestJS DI system.
Question 43: What does NestFactory.create() return?
- An Express app instance
- A controller registry
- A module reference
- A Promise resolving to an INestApplication instance (Correct answer)
Correct answer: A Promise resolving to an INestApplication instance
NestFactory.create() is async and returns a Promise<INestApplication>, which provides methods like listen(), use(), and enableCors().
Question 44: In NestJS, what is an injection token used for?
- Namespacing module routes
- Authenticating HTTP requests
- Labeling log messages
- Uniquely identifying a provider in the DI container (Correct answer)
Correct answer: Uniquely identifying a provider in the DI container
An injection token (string, Symbol, or class) uniquely identifies a provider in NestJS's IoC container so the correct value is injected.
Question 45: Which testing framework does NestJS use by default for unit and integration tests?
- Vitest
- Jasmine
- Jest (Correct answer)
- Mocha
Correct answer: Jest
NestJS uses Jest as its default testing framework, which is pre-configured when you scaffold a project with the Nest CLI.
Question 46: What is a Dynamic Module in NestJS?
- A module that dynamically creates routes
- A module that exports configuration-based providers at import time (Correct answer)
- A module with runtime-generated controllers
- A module loaded at runtime via lazy loading
Correct answer: A module that exports configuration-based providers at import time
A Dynamic Module returns a module configuration object (including providers) at import time, enabling customizable, reusable modules like ConfigModule.forRoot().
Question 47: How do you make a NestJS module available globally without importing it in every module?
- Use the @Global() decorator on the module (Correct answer)
- Add it to the AppModule's controllers array
- Register it in the bootstrap function
- Use @Injectable({ scope: Scope.DEFAULT })
Correct answer: Use the @Global() decorator on the module
The @Global() decorator marks a module as global-scope so its exported providers are available throughout the application without needing explicit imports.
Question 48: How do you enable CORS in a NestJS application?
- Use @CrossOrigin() on each controller
- Add CorsModule to AppModule imports
- Call app.enableCors() or pass cors option to NestFactory.create() (Correct answer)
- Install @nestjs/cors package and add @UseCors() decorator
Correct answer: Call app.enableCors() or pass cors option to NestFactory.create()
CORS is enabled by calling app.enableCors() with optional configuration options, or by passing `{ cors: true }` to NestFactory.create().
Question 49: In a NestJS application, which built-in utility validates and transforms incoming request payloads to reduce data-integrity risks?
- ExceptionFilter
- Interceptor
- ValidationPipe (Correct answer)
- Guard
Correct answer: ValidationPipe
ValidationPipe leverages class-validator and class-transformer to automatically validate DTOs, preventing malformed data from reaching business logic.
Question 50: What does a NestJS Pipe primarily do?
- Transforms and validates input data before it reaches the route handler (Correct answer)
- Filters out unauthorized requests
- Connects services to controllers
- Manages the application lifecycle
Correct answer: Transforms and validates input data before it reaches the route handler
Pipes implement the PipeTransform interface and are used to transform and/or validate data before it reaches the route handler.
Question 51: What does the `--coverage` flag do when running `jest` in a NestJS project?
- Limits test execution to files in the coverage whitelist
- Runs only tests marked with @CoverageTest() decorator
- Generates a code coverage report showing which lines/branches are tested (Correct answer)
- Enables verbose output for each test case
Correct answer: Generates a code coverage report showing which lines/branches are tested
The `--coverage` flag instruments the code and produces a report (HTML, text, lcov) showing the percentage of statements, branches, functions, and lines covered by tests.
Question 52: A stakeholder notices that API error messages expose internal stack traces in production. What NestJS configuration prevents this?
- Removing all try/catch blocks
- Using HTTP-only cookies
- Disabling all exception filters
- Setting app.useGlobalFilters() with a filter that omits stack in production (Correct answer)
Correct answer: Setting app.useGlobalFilters() with a filter that omits stack in production
A custom global exception filter can inspect NODE_ENV and strip stack trace details from the response in production.
Question 53: What does `useExisting` do in a NestJS custom provider?
- Imports a provider from another module
- Creates a new instance of an existing class
- Creates an alias that points to an already-registered provider (Correct answer)
- Marks a provider as optional
Correct answer: Creates an alias that points to an already-registered provider
`useExisting` creates a provider alias so two different tokens resolve to the same underlying provider instance.
Question 54: How do you implement soft deletes in TypeORM within a NestJS application?
- Set `softDelete: true` in TypeOrmModule.forRoot()
- Add `deleted: boolean` and filter manually in every query
- Use a TypeORM AfterRemove subscriber
- Use the @DeleteDateColumn() decorator and call repository.softDelete() (Correct answer)
Correct answer: Use the @DeleteDateColumn() decorator and call repository.softDelete()
@DeleteDateColumn() adds a nullable timestamp column; repository.softDelete() sets it instead of removing the row, and find queries automatically exclude soft-deleted records.
Question 55: Which TypeORM feature allows you to automatically set `createdAt` and `updatedAt` timestamps?
- @CreateDateColumn() and @UpdateDateColumn() decorators (Correct answer)
- @Auto() decorator
- Set `timestamps: true` in entity options
- @Timestamp() with auto option
Correct answer: @CreateDateColumn() and @UpdateDateColumn() decorators
@CreateDateColumn() and @UpdateDateColumn() are TypeORM column decorators that automatically populate timestamp fields on insert and update respectively.
Question 56: What does `AuthGuard('jwt')` do in NestJS?
- Generates a JWT token for the current user
- Refreshes an expired JWT automatically
- Signs outgoing responses with a JWT signature
- Validates the JWT token from the request and populates req.user (Correct answer)
Correct answer: Validates the JWT token from the request and populates req.user
AuthGuard('jwt') invokes the Passport JWT strategy to extract, verify, and decode the token, attaching the payload to req.user.
Question 57: What is the role of `TestingModule.resolve()` as opposed to `TestingModule.get()` in NestJS testing?
- `resolve()` compiles the module lazily; `get()` compiles it eagerly
- `resolve()` creates a new scoped/transient instance; `get()` returns the singleton (Correct answer)
- `resolve()` retrieves global providers; `get()` retrieves module-local providers
- `resolve()` is synchronous; `get()` is asynchronous
Correct answer: `resolve()` creates a new scoped/transient instance; `get()` returns the singleton
`resolve()` returns a new instance for REQUEST or TRANSIENT scoped providers on each call, while `get()` always returns the same singleton instance registered in the DI container.
Question 58: What is database connection pooling and why is it important in NestJS?
- Maintaining a set of reusable DB connections to reduce connection overhead under concurrent load (Correct answer)
- Caching database query results to avoid repeated SQL
- Batching multiple queries into a single network round trip
- Sharding database writes across multiple servers
Correct answer: Maintaining a set of reusable DB connections to reduce connection overhead under concurrent load
Connection pooling reuses established database connections across requests, avoiding the overhead of creating and tearing down connections for every query.
Question 59: Which decorator is used to inject a value by a custom token rather than a class type?
- @InjectToken()
- @ProvideWith()
- @UseToken()
- @Inject(TOKEN) (Correct answer)
Correct answer: @Inject(TOKEN)
@Inject(TOKEN) allows injecting custom providers registered with a string or Symbol token instead of a class reference.
Question 60: What does the `imports` array in @Module() accept?
- Middleware functions
- Service class references
- NPM package names
- Other module classes whose exported providers are needed (Correct answer)
Correct answer: Other module classes whose exported providers are needed
The `imports` array takes other NestJS module classes, making their exported providers available for injection within the importing module.
NestJS Developer Skills Assessment
Evaluates proficiency in the NestJS Node.js framework, covering core architecture, dependency injection, decorators, database integration, and advanced patterns for building scalable server-side applications.
Exam Rules
- You can skip questions and return to them later
- Flag questions for review before submitting
- No feedback shown until you submit the entire exam
- Unanswered questions count as wrong — answer everything
- 10 pretest questions are mixed in and don't affect your score
- Timer auto-submits when time runs out
- Your progress is auto-saved every 30 seconds