In a NestJS TestingModule, why does get() throw for a request-scoped provider, and how do resolve() and a context ID help?
answer
- static versus per-context instances
- scope travels up the dependency chain
- a fresh sub-tree per call
- pin the context identifier
basics
~20 sget() returns only static singletons, so a request-scoped or transient provider, or anything depending on one, throws InvalidClassScopeException. resolve() builds the instance in a DI sub-tree; each call gets a new one unless you pass the same contextId.
solid answer
~40 sA `TestingModule` offers the same resolution API as a module reference. `get()` returns the **static** instance created at `compile()`, and it throws `InvalidClassScopeException` ("...is marked as a scoped provider... Please, use \"resolve()\" instead.") for a `Scope.REQUEST` or `Scope.TRANSIENT` provider, and for a default-scoped one whose dependency tree contains a scoped provider, because no static instance exists. `resolve()` is asynchronous and builds the instance inside a DI container sub-tree identified by a context ID. Without a second argument it creates a new context ID every call, so two calls return different objects. To get the same instance twice, create one with `ContextIdFactory.create()` and pass it to every `resolve()`. In an end-to-end test, making `ContextIdFactory.getByRequest` return that ID lets you `resolve()` the very instance that served a request.
go deeper
Recall that get() is for ordinary singletons and resolve() is the asynchronous call for request-scoped or transient providers.
Explain scope bubbling, why get() checks the whole dependency tree, and why two resolve() calls without a context ID differ.
Show how to pin a context ID, including spying on ContextIdFactory.getByRequest to reach the instance that served an e2e request.
Weigh the testing and performance cost of request scope spreading through a graph before a team adopts it widely.
## Scopes in one paragraph By default every NestJS provider is a **singleton**: created once at startup and shared. A provider can opt into `Scope.REQUEST` (one instance per incoming request) or `Scope.TRANSIENT` (a new instance for each consumer that injects it). Scope also **travels up the chain**: a default-scoped service that injects a request-scoped one cannot be a singleton any more, so Nest builds it per request as well. Nest calls such a provider's dependency tree *non-static*. ## Why get() throws `get(token)` hands back the instance created during `compile()`. Before returning, it checks the provider's wrapper: if the scope is request or transient, or if the dependency tree is not static, it throws `InvalidClassScopeException` with a message that names the class and ends "Please, use \"resolve()\" instead." There is simply no single instance to return. - `Scope.REQUEST` provider: `get()` throws. - `Scope.TRANSIENT` provider: `get()` throws. - Default-scoped provider that depends on a request-scoped one: `get()` throws too, which surprises people who never marked it themselves. ## How resolve() works `resolve(token, contextId?, options?)` returns a **Promise**. It looks at the same wrapper: 1. If the dependency tree is static and the provider is not transient, it returns the existing singleton. 2. Otherwise it builds the instance (and its scoped dependencies) inside a **DI container sub-tree** keyed by a context identifier. 3. If you pass no `contextId`, it creates a new one for this call. The docs warn about the consequence of step 3: calling `resolve()` twice and comparing the references shows they are **not equal**, because each call got its own sub-tree. | Call | Static provider | Request-scoped provider | |---|---|---| | `get(X)` | the singleton | throws `InvalidClassScopeException` | | `resolve(X)` | the singleton | a new instance in a new sub-tree | | `resolve(X, id)` twice with the same `id` | the singleton | the same instance both times | ## Pinning a context ID To work with one stable instance, create the identifier yourself: ```typescript const contextId = ContextIdFactory.create(); const first = await moduleRef.resolve(OrderAuditLog, contextId); const second = await moduleRef.resolve(OrderAuditLog, contextId); // first === second ``` If the scoped provider injects the request object, `moduleRef.registerRequestByContextId(request, contextId)` registers a stand-in request for that sub-tree. ## Reaching the instance that served an HTTP request In an end-to-end test the request arrives through the HTTP adapter, and Nest derives its context ID from the request with `ContextIdFactory.getByRequest()`. The documented technique is to **spy on that static method** (with your test runner's spy utility) so it returns a context ID you created beforehand. Every request in the test then uses that sub-tree, and `await moduleRef.resolve(OrderAuditLog, contextId)` returns the same instance the handler used, so you can inspect what it recorded. ## Choosing the right call in a test - **Static services and controllers**: `get()`, which is synchronous and cheap. - **Request-scoped or transient providers, or anything that injects one**: `await resolve()`. - **Two steps that must see the same scoped instance**: create one context ID and pass it to both `resolve()` calls. - **The instance a real HTTP request used**: pin `ContextIdFactory.getByRequest` as described above. - **Scope that does not matter to this test**: replace the scoped provider with `overrideProvider(...).useValue(fake)`. A value override is registered as a default-scoped instance, so the fake, and the services that inject it, become static again and `get()` works. The last option is often the simplest for a service test, but it removes the very per-request behaviour you might want to check, so keep at least one test that resolves the real scoped provider. ## Common mistakes - Using `get()` because "it worked before", then adding a request-scoped dependency deep in the graph and seeing a distant test fail. - Forgetting `await` on `resolve()` and asserting on a Promise. - Calling `resolve()` without a context ID in two places and expecting to observe the same state. - Assuming a value supplied with `overrideProvider(...).useValue()` keeps the original's request scope: a value override is treated as a default-scoped static instance.
- In NestJS, why does a default-scoped OrdersService start failing with get() after someone adds a request-scoped dependency to it?Scope bubbles up the injection chain. Once `OrdersService` depends on a request-scoped provider, Nest can no longer build it once at startup, so its dependency tree is non-static and it is created per request. `get()` checks exactly that and throws `InvalidClassScopeException`; switching the test to `await moduleRef.resolve(OrdersService, contextId)` fixes it.
- In a NestJS e2e test, how do you inspect the request-scoped instance that handled a Supertest request?Create a context ID with `ContextIdFactory.create()`, then use the test runner's spy utility to make `ContextIdFactory.getByRequest` return it. Every incoming request now builds its scoped providers in that one sub-tree, so `await moduleRef.resolve(Provider, contextId)` after the request returns the instance the handler used.
- get() creates a fresh instance for request-scoped providers
- resolve() always returns the same instance for a token
- Only classes marked Scope.REQUEST themselves can make get() throw
- resolve() is synchronous like get()
- A useValue override inherits the original provider's request scope