CodePark/ questions / Testing NestJS apps
START PRACTICINGPRACTICE
Backend question · Backend testing › Testing NestJS apps

CartService is @Injectable({ scope: Scope.REQUEST }). In a test, moduleRef.get(CartService) throws. What is the correct way to get an instance?

Use await moduleRef.resolve(CartService), passing a shared contextId from ContextIdFactory.create() when you need the same instance across calls

Use await moduleRef.resolve(CartService). get() only returns static singletons (one shared instance). It throws for request-scoped or transient-scoped providers.

resolve() builds an instance for a context (one request). It returns a new instance on every call, unless you pass the same context id. Create a shared id with ContextIdFactory.create(). The Nest docs also show spying on ContextIdFactory.getByRequest, so nested request-scoped dependencies share that same context.

"Use
moduleRef.get(CartService, { strict: false })" is wrong: strict: false only changes where Nest looks for the provider, and get() still throws for scoped providers. Request-scoped providers can be tested without supertest, through resolve().