tezvyn:

Angular Unit Testing: Jasmine & Karma

AI-drafted, machine-checkedSource: angular.devbeginner
Angular Unit Testing: Jasmine & Karma

Jasmine is your testing script (`expect(a).toBe(b)`), while Karma is the stage that runs it in a browser. This is Angular's default stack for unit testing components and services to ensure they work in isolation.

WHY IT EXISTS To ensure individual parts of an Angular app, like components and services, work correctly in isolation. This practice, called unit testing, catches bugs early, prevents future regressions, and makes code safer to refactor. It's a foundational practice for maintaining large, complex applications.

THE MENTAL MODEL Jasmine is the testing framework that gives you the language to write tests, while Karma is the test runner that executes those tests. Think of Jasmine as the sheet music (describe suites, it specs, expect assertions) and Karma as the orchestra that plays the music inside a real browser and reports if any notes were wrong.

HOW IT WORKS When you run ng test, the Angular CLI uses Karma's configuration file (karma.conf.js) to launch a browser. Karma then loads your test files and uses the Jasmine framework to execute the tests. Angular's TestBed is a critical utility that creates a sandboxed Angular module for each test, allowing you to create components and inject mock services. This isolates the unit under test from the rest of your application. You use Jasmine's expect() function with matchers like .toBe() or .toHaveBeenCalled() to assert that your code behaves correctly.

WHEN TO USE IT This is the default, out-of-the-box solution for unit testing in projects generated with the Angular CLI. Use it to test the public API of your components, services, and pipes. This includes checking a component's state based on its inputs, verifying a service's business logic, or ensuring a pipe transforms data correctly.

WHEN NOT TO USE IT This stack is not designed for end-to-end (E2E) tests, which simulate a complete user journey through the live application. For that, you would use a tool like Cypress or Playwright. It's also overkill for testing simple, framework-agnostic helper functions that don't need a browser environment; a Node-based runner like Jest can be faster for those cases.

ONE CANONICAL EXAMPLE To test an Angular service, you first configure a testing module using TestBed.configureTestingModule. Inside a test spec (an it block), you get an instance of the service using TestBed.inject(). You then call a public method on the service and use an expect assertion to verify the result. For example: expect(myService.add(2, 2)).toBe(4);.

Read the original → angular.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.