liveBook · Manning

TestBed

As explained in Modern Angular

TestBed is Angular's testing utility for configuring an isolated testing environment and creating or interacting with Angular artifacts.

TestBed configures an isolated Angular testing environment and provides access to services or components under test. For signal-based services, it supplies the setup needed to create a stub component and trigger change detection manually. section 8.3.5

Listing 8.15 Using a stub component to test a service with signals
@Component({
    selector: 'app-stub',
    template: '',
    standalone: true,
})
export class StubComponent {  #1
    constructor(private readonly service: TimeOffManagementService) {}
}

describe ('TimeOffManagementService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [MockProvider(TimeOffRequestService, MockTimeOffRequestService)],
            imports: [StubComponent],  #2
        });
        localStorageMock = {
          getItem: jest.fn().mockReturnValue(() => selectedType),
          setItem: jest.fn().mockImplementation((key, value) => {
            selectedType = value;
          })
        };
        Object.defineProperty(window, 'localStorage', {
          value: localStorageMock,
        });
        service = TestBed.inject(
                    TimeOffManagementService,
                  );  #3
    });

    it('should be successfully instantiated', () => {
        expect(service).toBeTruthy();
    });

    it('should have all requests loaded initially, () => {
        const fixture = TestBed.createComponent(StubComponent);
        fixture.detectChanges();  #4
        expect(service.requests())
          .toEqual(mockRequests);  #5
    });
});

Use the stub-component listing to see TestBed configuration, dependency mocking, service injection, and the test environment setup together. section 8.3.5

How Modern Angular covers it

How deep it goes
Explains configuration, injection, component creation, and change detection, while stopping short of deeper TestBed internals.
Examples
Uses a standalone stub component, mocked services, injected services, fixtures, and request-status signal assertions.
What it assumes
Assumes familiarity with Angular services, components, signals, dependency mocking, and unit-test assertions.
What you can do after
Diagnose signal-driven service behavior by configuring TestBed, injecting dependencies, triggering change detection, and checking results.
How it connects
Connects TestBed with Angular signals, dependency mocking, standalone components, and Angular change detection.

Also explained in

Compare how 2 books explain TestBed →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.