Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober 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 desk7 min

How to Test Angular Apps with Jasmine and Karma

A version-aware Angular guide to configuring Karma, writing Jasmine tests with TestBed and ComponentFixture, running tests, and debugging common setup issues.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To test an Angular app with Jasmine and Karma, configure the project’s Angular CLI test target to use Karma, write Jasmine specs, and run them with ng test. This workflow remains supported and is especially relevant to existing projects. New Angular CLI projects currently default to Vitest, so check your project’s test target before following the Karma setup steps.

What Jasmine and Karma each do

Jasmine is the test framework: it provides describe and it for organizing tests, expect for assertions, and spies for observing or replacing function calls. Karma is the runner that launches tests in a browser. Angular’s testing utilities, including TestBed and ComponentFixture, provide the Angular-specific environment for configuring dependencies and checking component behavior.

As an Amazon Associate I earn from qualifying purchases.

Angular documents Karma as supported alongside its newer default, Vitest. See the Angular testing overview and Karma and Jasmine guide. Which setup applies depends on your Angular CLI version and the test target in angular.json.

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

Choose the right setup for your project

Starting a new project with Karma

Ask Angular CLI to configure Karma when creating the project:

ng new my-karma-app --test-runner=karma

This explicitly selects Karma rather than relying on the current new-project default, which is Vitest.

Using an existing project

Inspect angular.json and find the application’s test target. Angular’s documented setup uses the @angular/build:unit-test builder with "runner": "karma". A simplified target looks like this; preserve the rest of your project’s existing options and configuration:

{
  "projects": {
    "my-app": {
      "architect": {
        "test": {
          "builder": "@angular/build:unit-test",
          "options": {
            "runner": "karma"
          }
        }
      }
    }
  }
}

Builder names and supported options can vary with Angular CLI generation. Check the Angular Karma guide for your version before copying configuration verbatim.

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

Install the Karma and Jasmine packages

For an existing project that does not already include them, Angular’s guide lists these package families: karma, karma-chrome-launcher, karma-coverage, karma-jasmine, karma-jasmine-html-reporter, jasmine-core, and @types/jasmine. Install the corresponding packages using your project’s package manager and version conventions, checking compatibility with the Angular version in use. Angular CLI can construct the Karma/Jasmine configuration from test-target options, so not every project needs a manually maintained Karma config file.

Enable Jasmine types in TypeScript

If TypeScript does not recognize the global Jasmine functions, include jasmine in compilerOptions.types in tsconfig.spec.json:

{
  "compilerOptions": {
    "types": ["jasmine"]
  }
}

If the file already has a types array, add jasmine without removing its other entries.

Write a service test

For Angular services, configure the testing environment and retrieve dependencies through the test injector. This example tests a service’s returned value; replace the service and expected value with the behavior in your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { TestBed } from '@angular/core/testing';
import { GreetingService } from './greeting.service';

describe('GreetingService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [GreetingService]
    });
  });

  it('returns a greeting', () => {
    const service = TestBed.inject(GreetingService);
    expect(service.greet('Ada')).toBe('Hello, Ada');
  });
});

Jasmine defines the suite, test, and assertion. TestBed configures Angular’s testing injector and resolves the service. Keep each test focused on observable behavior rather than implementation details.

Test a component and its rendered behavior

Use TestBed to provide a component’s imports and dependencies, then call TestBed.createComponent to get a ComponentFixture. The fixture exposes both the component instance and its rendered view. Call detectChanges() when you want Angular to update the view before making assertions.

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { GreetingComponent } from './greeting.component';

describe('GreetingComponent', () => {
  let fixture: ComponentFixture<GreetingComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [GreetingComponent]
    }).compileComponents();

    fixture = TestBed.createComponent(GreetingComponent);
    fixture.detectChanges();
  });

  it('renders its initial greeting', () => {
    const text = fixture.nativeElement.querySelector('h1').textContent;
    expect(text).toContain('Hello');
  });
});

This example assumes GreetingComponent is standalone. For a component declared in an NgModule, configure the relevant module or declare the component as appropriate for that application. Include the component’s required imports and providers in the test configuration.

Check an input or dependency change

Set an input on the component instance, trigger change detection, and assert the rendered result. Adapt the input name and expected text to the component:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
it('renders the supplied name', () => {
  fixture.componentInstance.name = 'Ada';
  fixture.detectChanges();

  const text = fixture.nativeElement.querySelector('h1').textContent;
  expect(text).toContain('Ada');
});

When testing a service-backed component, provide a test double in the testing configuration, then assert the user-visible outcome. This keeps the test independent of network access or unrelated service implementation.

Check a user interaction

Trigger the same DOM event the component responds to, then run change detection and verify the result. For a button with an Angular click handler:

it('updates the view after a click', () => {
  const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
  button.click();
  fixture.detectChanges();

  expect(fixture.nativeElement.textContent).toContain('Saved');
});

Use assertions that reflect the outcome a user can observe. If the interaction schedules asynchronous work, wait for that work using an explicit async pattern before checking the updated view.

Test asynchronous behavior deliberately

For native promises, make the Jasmine test function async and await the operation before asserting. For Angular work that must settle before reading the view, use the fixture’s stability mechanism where it fits:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
it('renders after asynchronous work settles', async () => {
  await fixture.whenStable();
  fixture.detectChanges();

  expect(fixture.nativeElement.textContent).toContain('Loaded');
});

Choose an approach that matches the operation under test. Angular’s testing APIs are distinct from Jasmine’s runner conventions; legacy Zone.js helpers should not be treated as universal Jasmine/Karma features.

Run tests and debug failures

Run in watch mode

From the Angular workspace, run:

ng test

In the documented Karma workflow, this builds and launches the configured runner in watch mode; changes trigger another test run. The behavior depends on the project’s test target and CLI version.

Run a headless, single CI pass

Angular’s Karma guide documents this CI-style command:

ng test --no-watch --no-progress --browsers=ChromeHeadless

It disables watch mode and progress output and selects the Chrome headless browser launcher. Make sure the project has a compatible browser launcher and that Chrome is available in the CI environment. Exact option support can depend on the Angular CLI version and configured runner.

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

Debug in a browser

When a test fails in the browser, use Karma’s browser window and its DEBUG tab to run the tests in a debuggable context. Open the browser’s developer tools, set breakpoints in the relevant spec or application code, and inspect the state when the test pauses. For custom Karma configuration, Angular documents generating a configuration file with:

ng generate config karma

Generate one only when you need settings beyond the CLI’s test-target options.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common setup problems

  • describe, it, or expect is unknown to TypeScript: check that the spec TypeScript configuration includes "jasmine" in compilerOptions.types, and that @types/jasmine is installed.
  • ng test runs Vitest instead of Karma: inspect the application’s test target in angular.json. Configure the supported test builder and set its runner to karma as documented for your Angular CLI version.
  • The browser does not launch in CI: verify that the configured browser launcher is installed and that the selected browser is available to the CI job. Angular’s documented headless example selects ChromeHeadless; it does not install Chrome for you.
  • A component test reports missing dependencies or imports: add the component’s required imports and providers to TestBed.configureTestingModule, or provide an appropriate test double for dependencies not under test.
  • The DOM assertion sees stale content: after changing component state or dispatching an event, call fixture.detectChanges() before reading the rendered view. If asynchronous work is involved, await its completion or fixture stability first.
  • A custom Karma configuration no longer matches the CLI setup: compare the configuration with the project’s test target and Angular CLI version. Generate a Karma config only for settings the CLI options do not cover.

When to keep Karma and when to consider Vitest

For an established project, retaining Karma can avoid reworking existing Jasmine specs, custom browser launchers, reporters, plugins, and test-specific configuration. It also preserves browser-based execution where that is part of the team’s testing needs. Review the project’s current Angular CLI support and actual test target rather than assuming every Angular project uses the same runner.

For a new project, Angular CLI currently defaults to Vitest with jsdom. Angular’s migration guide describes moving from Karma and Jasmine to Vitest as experimental, requiring the application build system, and potentially requiring manual review. Migration can involve installing Vitest and a DOM emulator, changing the test builder, reviewing old target build options, and replacing or moving custom Karma configuration. The refactoring schematic converts some common Jasmine patterns but does not handle every complex case; Angular advises reviewing its changes. Browser mode is also available through providers such as Playwright or WebdriverIO. Migration is an option, not a requirement for existing projects. See the Angular Vitest migration guide.

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

Or skip the browser setup

For website screenshots rather than Angular unit tests, ScreenshotNeo is a screenshot API and MCP server. A single GET request captures a URL as an image or PDF; use it to capture rendered pages, not as a replacement for Jasmine/Karma tests.

cURL example, with the API options documented at ScreenshotNeo docs:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie banners, popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks, blank pages, and failed loads are never billed; responses identify the page verdict and billing status.
  • An MCP server lets AI agents use screenshot and page-info tools.
  • The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Does Jasmine provide Angular’s component-testing utilities?

No. Jasmine supplies test structure, assertions, and spies; Angular’s TestBed and ComponentFixture provide the Angular testing environment.

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

Do I need to create a karma.conf.js file?

Not necessarily. Angular CLI can build Karma configuration from test-target options; generate a Karma config only when you need custom settings.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.