Sub topic 12
Testing deferred blocks with TestBed
This chapter assumes you can write standalone components, know the @defer block with its @placeholder, @loading and @error sub-blocks, and have used TestBed for component tests. You will learn how to drive a deferred block through its states in a unit test.
Why deferred blocks need special handling
In a running app, a @defer block moves through states on its own. It starts with the placeholder, may show the loading content, and ends in the complete or error state. Each step depends on triggers and on a chunk download.
A test cannot wait for a real viewport or a real network request. TestBed therefore gives you control over the block. You choose which state it renders and when.
The two behaviors
TestBed has a deferBlockBehavior option with two values from DeferBlockBehavior:
| Behavior | What happens | When to use it |
|---|---|---|
| `Playthrough` | Blocks follow their triggers as in a real app. This is the default. | Tests that check real trigger behavior. |
| `Manual` | Blocks stay in the placeholder state until the test renders them. | Tests that check one specific state. |
Use Manual for most tests. The result does not depend on timers or on browser APIs such as IntersectionObserver.
Rendering the complete state
The component under test uses a viewport trigger and a placeholder:
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post',
imports: [CommentsComponent],
template: `
<article>...</article>
@defer (on viewport) {
<app-comments />
} @placeholder {
<div class="comments-placeholder"></div>
}
`,
})
export class PostComponent {}The test sets the behavior to Manual, creates the fixture, and asks for its defer blocks:
import { TestBed, DeferBlockBehavior, DeferBlockState } from '@angular/core/testing';
import { PostComponent } from './post.component';
it('renders the deferred comments', async () => {
TestBed.configureTestingModule({
imports: [PostComponent],
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Complete);
expect(fixture.nativeElement.querySelector('app-comments')).not.toBeNull();
});getDeferBlocks() returns one entry for each @defer block in the template, in template order. Nested blocks appear as well. Calling render() on an entry moves that block to the state you pass in.
The states you can render
DeferBlockState has four values:
Placeholdershows the@placeholdercontent.Loadingshows the@loadingcontent.Completeshows the main content.Errorshows the@errorcontent.
A block must be in the placeholder state before you can move it elsewhere. In Manual mode it starts there, so you can render any state directly.
Testing placeholder and error content
You can check every sub-block with the same pattern. This test uses a template that includes @placeholder, @loading and @error:
it('shows the error content when loading fails', async () => {
TestBed.configureTestingModule({
imports: [PostComponent],
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Error);
expect(fixture.nativeElement.textContent).toContain('Comments could not be loaded.');
});This is the only practical way to cover the error branch. Forcing a real chunk failure in a unit test is slow and fragile.
Common errors
- The deferred content never appears. In
Playthroughmode the trigger never fires in a test environment. Switch toManualand callrender(). blocks[0]is undefined. The template has no@deferblock, or you calledgetDeferBlocks()before the fixture was created. Check the template and the order of calls.- Wrong block rendered. With several blocks, the index follows template order. Assert on content that belongs to the block you meant.
- Forgetting
await. BothgetDeferBlocks()andrender()return promises. Withoutawait, the assertion runs before the DOM updates.
Exercise
A test uses the default TestBed configuration and expects <app-chart /> inside @defer (on interaction(showChart)) to appear, but the assertion fails. What change lets the test render the block without simulating a click, and which call finishes the job?
Show answer
Set deferBlockBehavior: DeferBlockBehavior.Manual in configureTestingModule. Then get the blocks with await fixture.getDeferBlocks() and call await blocks[0].render(DeferBlockState.Complete) before asserting.
Exercise
Which DeferBlockState would you render to test that a template shows "Comments could not be loaded."?
Show answer
DeferBlockState.Error, passed to render() on the matching block.