Skip to content

Commit b6b833e

Browse files
Add a section for overriding APP_* token providers
This adds a section on how to replace `APP_*` token providers in testing. This follows the description by @kamilmysliwiec in nestjs/nest#4053 . I've used the solution in my project and it worked great. Thanks to @jmcdo29 who pointed me to that issue when I was struggling with this.
1 parent b6b10d0 commit b6b833e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

content/fundamentals/unit-testing.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,46 @@ The compiled module has several useful methods, as described in the following ta
312312
313313
> info **Hint** Keep your e2e test files inside the `e2e` directory. The testing files should have a `.e2e-spec` or `.e2e-test` suffix.
314314
315+
#### Overriding globally registered providers
316+
317+
If you have a [globally registered guard](/security/authentication#enable-authentication-globally) (or pipe, interceptor, or filter), you need to take a few more steps to override that enhancer. To re-cap the original registration looks like this:
318+
319+
```typescript
320+
providers: [
321+
{
322+
provide: APP_GUARD,
323+
useClass: JwtAuthGuard,
324+
},
325+
],
326+
```
327+
328+
This is registering the guard as a "multi"-provider through the `APP_*` token. To be able to replace the JwtAuthGuard here, the registration needs to use an existing provider in this slot:
329+
330+
```typescript
331+
providers: [
332+
{
333+
provide: APP_GUARD,
334+
useExisting: JwtAuthGuard,
335+
},
336+
JwtAuthGuard,
337+
],
338+
```
339+
340+
> info **Hint** Change the `useClass` to `useExisting` to reference a registered provider instead of having Nest instantiate it behind the token.
341+
342+
Now the `JwtAuthGuard` is visible to nest as a regular provider that can be overridden when creating the test module:
343+
344+
```typescript
345+
const moduleRef = await Test.createTestingModule({
346+
imports: [AppModule],
347+
})
348+
.overrideProvider(JwtAuthGuard)
349+
.useClass(MockAuthGuard)
350+
.compile();
351+
```
352+
353+
Now all your tests will use the `MockAuthGuard` on every request.
354+
315355
#### Testing request-scoped instances
316356

317357
[Request-scoped](/fundamentals/injection-scopes) providers are created uniquely for each incoming **request**. The instance is garbage-collected after the request has completed processing. This poses a problem, because we can't access a dependency injection sub-tree generated specifically for a tested request.

0 commit comments

Comments
 (0)