Sub topic 12
Testing deferred blocks with TestBed
This chapter assumes you have written a @defer block with @placeholder, @loading and @error sub-blocks, and that you know the basics of TestBed and ComponentFixture. Here you will learn how Angular's test utilities let you drive a deferred block through its states without waiting for real triggers or real network requests.
Why deferred blocks need special handling in tests
In the browser, a deferred block changes state on its own. A trigger fires, the chunk downloads, and the block moves from placeholder to loading to complete. A unit test cannot rely on that timeline:
- Triggers such as
on viewportdepend on browser APIs likeIntersectionObserver, which a test environment may not provide or may not fire. - Timers such as
on timer(5s)orminimum 1smake tests slow and flaky. - Assertions on the loading and error states need a way to stop the block in that state.
TestBed solves this with a configuration option, deferBlockBehavior, and with a fixture method, getDeferBlocks(). Together they let the test choose the state of each block directly.
The two behaviors
deferBlockBehavior accepts a value from the DeferBlockBehavior enum.
| Value | What happens | Use it for |
|---|---|---|
| `DeferBlockBehavior.Playthrough` | Blocks behave as they do in an app. Triggers fire and blocks move through states on their own. | Integration-style tests where you want the real flow. |
| `DeferBlockBehavior.Manual` | Blocks stay in their initial state until the test renders them. | Unit tests of one specific state. |
Set the option explicitly in every test file that touches deferred content. Then the test does not depend on the default of the Angular version you happen to use.
In Manual mode, the block starts in its initial state. That is the placeholder if you wrote a @placeholder block, and nothing if you did not. No trigger runs, so the deferred content never appears unless the test asks for it.
The component under test
The examples use a small post page. The comments are deferred until they scroll into view.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-comments',
template: `<section class="comments">Comments for post {{ postId() }}</section>`,
})
export class CommentsComponent {
readonly postId = input.required<number>();
}import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post',
imports: [CommentsComponent],
template: `
<article>Post body</article>
@defer (on viewport) {
<app-comments [postId]="42" />
} @placeholder {
<div class="comments-placeholder">Scroll to load comments</div>
} @loading (after 100ms; minimum 1s) {
<p class="comments-loading">Loading comments...</p>
} @error {
<p class="comments-error">Comments could not be loaded.</p>
}
`,
})
export class PostComponent {}Getting the blocks from a fixture
After you create the fixture, call fixture.getDeferBlocks(). It returns a promise for an array of DeferBlockFixture objects, one for each @defer block in the component's template, in template order. Each object has a render(state) method. The method returns a promise, so always await it.
The states come from the DeferBlockState enum:
DeferBlockState.PlaceholderDeferBlockState.LoadingDeferBlockState.CompleteDeferBlockState.Error
The diagram shows the states you can request and how they relate in a real run. In Manual mode you may jump to any state that has a matching sub-block, in any order.
Testing the complete state
The first test renders the deferred content and checks that it is in the DOM.
import { TestBed, DeferBlockBehavior, DeferBlockState } from '@angular/core/testing';
import { PostComponent } from './post.component';
describe('PostComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [PostComponent],
deferBlockBehavior: DeferBlockBehavior.Manual,
});
});
it('renders the deferred comments', async () => {
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Complete);
expect(fixture.nativeElement.querySelector('app-comments')).not.toBeNull();
});
});render(DeferBlockState.Complete) loads the block's dependencies, creates the deferred view and runs change detection. You do not need to call fixture.detectChanges() afterward for the block itself.
Testing the other states
Because each sub-block is a separate state, give each one its own test.
it('shows the placeholder before anything loads', async () => {
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Placeholder);
const el: HTMLElement = fixture.nativeElement;
expect(el.querySelector('.comments-placeholder')).not.toBeNull();
expect(el.querySelector('app-comments')).toBeNull();
});
it('shows the loading message', async () => {
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Loading);
expect(fixture.nativeElement.querySelector('.comments-loading')).not.toBeNull();
});
it('shows the error message', async () => {
const fixture = TestBed.createComponent(PostComponent);
const blocks = await fixture.getDeferBlocks();
await blocks[0].render(DeferBlockState.Error);
expect(fixture.nativeElement.querySelector('.comments-error')).not.toBeNull();
});These tests never wait for after 100ms or minimum 1s. In Manual mode the timing parameters do not delay the state you request. That makes Manual the better choice for checking the visual state of a block.
The Error test does not simulate a failed download. It asks Angular to show the error view. If you need to prove that your app recovers from a real failure, that is an end-to-end concern, not a unit test.
A missing sub-block is an error
Asking for a state the template does not define fails the test. If the template above had no @loading block, render(DeferBlockState.Loading) would throw, and so would Error without @error. This is useful. When a test throws here, it often means the template is missing a block you assumed was there.
The inverse also holds. Do not write a test for a state that the user can never see.
Several blocks in one template
When a template has more than one @defer, the array from getDeferBlocks() follows template order. Index 0 is the first block in the template. Reordering the template silently changes which block blocks[0] refers to, so keep tests close to the template they cover. For readability, assign named constants:
const [comments, related] = await fixture.getDeferBlocks();
await comments.render(DeferBlockState.Complete);
await related.render(DeferBlockState.Placeholder);A block nested inside another deferred block does not exist until the outer block is rendered. Render the outer block first, then ask the fixture for its blocks again.
Playthrough mode
Use Playthrough when you want to check that triggers and sub-blocks work together. The block runs through its real lifecycle, so the test must let it finish before asserting.
it('loads on idle without manual control', async () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [PostComponent],
deferBlockBehavior: DeferBlockBehavior.Playthrough,
});
const fixture = TestBed.createComponent(PostComponent);
fixture.detectChanges();
await fixture.whenStable();
expect(fixture.nativeElement.querySelector('.comments-placeholder')).not.toBeNull();
});This test passes for a viewport trigger because nothing scrolls the element into view. For a block with on idle or on immediate, the same wait would end with the deferred content on screen. Playthrough tests are only as reliable as the trigger. Triggers that need IntersectionObserver or real user events usually belong in Manual tests or in browser-level tests.
Common mistakes
- Forgetting
await.getDeferBlocks()andrender()both return promises. Withoutawait, the assertion runs before the view exists and the test fails or, worse, passes on a stale DOM. - Using the default behavior without checking it. If the default differs from what you assume, a test may pass in one Angular version and fail in another. Set
deferBlockBehaviorexplicitly. - Asserting on an eagerly imported component. A component used only in the deferred block should not appear in the DOM before rendering. If your test finds it too early, check that the template does not reference it elsewhere. A second use outside the block keeps the dependency in the main bundle and defeats the split.
- Reusing the module configuration across tests.
deferBlockBehavioris part of the module configuration. Set it once inbeforeEach, or callTestBed.resetTestingModule()before reconfiguring, as the Playthrough example does. - Testing the bundle split in a unit test.
TestBeddoes not prove that a separate chunk is created. Verify chunking in the production build output.
What to test and what to skip
Unit tests are well suited to the visible contract of the block:
- The placeholder is shown before loading, and it has the content and size you expect.
- The deferred component receives the right inputs once it is complete.
- The error message is shown in the error state.
- Anything the user must be able to do in a given state is possible.
Skip the framework's own behavior. You do not need a test that @defer loads a chunk, or that minimum 500ms waits for 500 milliseconds. Those are Angular's responsibilities.
Exercises
Exercise
A template contains a @defer block with a @placeholder and an @error block, but no @loading block. What happens if a test calls render(DeferBlockState.Loading), and why?
Show answer
The call fails with an error. render can only show a state whose sub-block exists in the template. Without @loading there is no view to render for that state.
Exercise
Write the TestBed configuration and the first two lines of a test that give you full manual control over the first deferred block of PostComponent.
Show answer
Configure the module with deferBlockBehavior: DeferBlockBehavior.Manual, for example TestBed.configureTestingModule({ imports: [PostComponent], deferBlockBehavior: DeferBlockBehavior.Manual });. Then create the fixture with const fixture = TestBed.createComponent(PostComponent); and get the blocks with const blocks = await fixture.getDeferBlocks();. After that, blocks[0] is the first block, and await blocks[0].render(DeferBlockState.Complete) renders it.
Exercise
A teammate's test passes await blocks[0].render(DeferBlockState.Complete) but then reads the DOM and finds the placeholder still on screen. The test file sets no deferBlockBehavior. Name one thing to check first.
Show answer
Set deferBlockBehavior explicitly, for example to DeferBlockBehavior.Manual, so the block does not depend on the version default. Also check that getDeferBlocks() was awaited and that blocks[0] is the block the assertion is about, because a template with several @defer blocks makes the index easy to get wrong.