Skip to content

Commit ccce2be

Browse files
Merge pull request #1578 from davids-sparkshare/patch-1
Add a section for overriding APP_* token providers
2 parents 3e3c55a + ce1cf76 commit ccce2be

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 enhancers
316+
317+
If you have a globally registered guard (or pipe, interceptor, or filter), you need to take a few more steps to override that enhancer. To recap 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 `TestingModule`:
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)