DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

Basics of Testing Components in Angular

Create Angular components in TestBed, inspect what the template renders, and test user interactions with ComponentFixture.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To test an Angular component, check more than its TypeScript class: create it in Angular’s test environment, render its template, and assert what a user sees or how it responds to an action. A class-only test can validate logic, but it cannot prove that the template displays the right result.

How do I test an Angular component?

Angular components combine a TypeScript class with an HTML template. A component test can exercise that combination by creating the component and inspecting its rendered host element. This is useful when the behavior under test affects visible content, bindings, or user interaction. For logic that does not depend on a component or template, a class or service test can be a simpler fit.

Angular’s current testing overview says new Angular CLI projects use Vitest with jsdom by default and run tests with ng test. Karma remains supported for existing projects. These defaults describe the CLI guidance, not every Angular version or custom workspace; check your project’s configured runner if its setup differs. Angular testing overview

Set up the component before creating it

TestBed configures the Angular test environment, including the component and any required imports or providers. For a standalone component, add it to the test configuration’s imports as appropriate. Configure or override the test setup before calling TestBed.createComponent(...): component creation freezes the current TestBed definition.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

TestBed.createComponent(ComponentName) creates the component and returns a ComponentFixture. The fixture gives the test access to the component instance and its rendered host, as well as controls such as change detection. Angular’s component-testing basics

Make a basic creation assertion

A minimal test can confirm that Angular creates the component. For example, in a test file where Banner is already imported and configured:

const fixture = TestBed.createComponent(Banner);
const component = fixture.componentInstance;
expect(component).toBeTruthy();

This checks creation, not whether the template displays the intended content. Use a rendered DOM assertion when the result matters to users.

How do I test what a component renders?

Run change detection so Angular applies bindings to the template, then inspect the fixture’s host element. In a DOM-based environment such as the CLI’s documented jsdom default for new projects, a test might look like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const fixture = TestBed.createComponent(Banner);
fixture.detectChanges();

const host = fixture.nativeElement as HTMLElement;
expect(host.textContent).toContain('Welcome');

Use an assertion tied to the behavior you intend to preserve: visible text, an element’s presence, or a value derived from component state. The exact selector and expected text depend on the component. nativeElement is the underlying host element; its concrete type depends on the test runtime. Angular’s DebugElement abstraction can be useful when you want an Angular-facing way to inspect elements across runtimes where native elements differ. Angular testing utility APIs

What is TestBed in Angular testing?

TestBed is Angular’s primary API for setting up unit tests. It prepares the test environment so Angular can create the component with the imports and providers the test needs. The fixture returned by createComponent is the test’s handle on the created component and its host element.

A common arrangement is to configure once for a test suite and create a fresh fixture for each test:

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [Banner],
  });
});

test('creates the banner', () => {
  const fixture = TestBed.createComponent(Banner);
  expect(fixture.componentInstance).toBeTruthy();
});

This example assumes Banner is standalone. Non-standalone components or components with additional dependencies need configuration suited to their setup. Do not try to reconfigure TestBed after creating a component in that test setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I test a button click or user interaction?

Trigger the user-facing event, run change detection if needed, and assert the resulting rendered behavior. For a component with a button that updates visible text, the pattern is:

const fixture = TestBed.createComponent(Counter);
fixture.detectChanges();

const host = fixture.nativeElement as HTMLElement;
host.querySelector('button')!.click();
fixture.detectChanges();

expect(host.textContent).toContain('1');

Replace the selector and expected result with the component’s actual UI. The important check is the outcome a user would observe, not merely that a method was called. If a test changes component state directly rather than through an event, call fixture.detectChanges() when the template needs to be updated. For asynchronous rendering, wait for the relevant work to settle before asserting; Angular’s component examples demonstrate waiting for stability where needed. Angular component testing scenarios

Do I need compileComponents()?

Not for a basic component test. Angular’s current component-testing basics guide says compileComponents() is only required when the tested components use @defer blocks. Do not add it reflexively to a minimal setup; older versioned examples may show conventions that differ from the current guide. Angular’s component-testing basics

When should I use a component harness?

Direct fixture DOM queries are suitable for a first test of a component you own. For Angular Material or another component library that provides test harnesses, a harness offers a testing interface for interacting with that component, and Angular documents loaders used with a TestBed fixture. Harnesses are an optional follow-on, not a prerequisite for a plain DOM assertion. Angular guide to component harnesses

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.