100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
TypeScript

Unit Testing with Jasmine and Karma

Learn how Angular's default testing stack—Jasmine for specs and Karma for running them in a real browser—verifies component logic, services, and pipes in isolation.

Testing & DeploymentIntermediate10 min readJul 9, 2026
Analogies

Unit Testing with Jasmine and Karma

Angular's classic testing setup pairs two independent tools. Jasmine is a behavior-driven testing framework that supplies the vocabulary for writing specs: describe() blocks group related tests, it() blocks define individual expectations, and matchers like toBe(), toEqual(), and toHaveBeenCalled() assert outcomes. Karma is the test runner—it launches a real browser (or a headless one such as ChromeHeadless), injects your compiled spec files, executes them, and reports pass/fail results back to the terminal or CI pipeline. The Angular CLI wires these together automatically: ng generate creates a *.spec.ts file alongside every component, service, and pipe, and ng test boots Karma with a preconfigured karma.conf.js. Newer Angular CLI versions (17+) have shifted the default builder toward Jest or Web Test Runner for some starter projects, but Jasmine/Karma remains the long-standing default and is still widely used in production codebases and interview contexts.

🏏

Cricket analogy: Jasmine and Karma pairing is like a coaching manual (Jasmine) providing drill vocabulary — describe a session, define a drill, assert a technique is correct — while a real net session (Karma) actually runs the players through it and reports who passed, with the CLI auto-generating a scoresheet template for every new player.

Anatomy of a Spec File

A spec file mirrors the structure of the code it tests. The outer describe() names the unit under test, a beforeEach() block resets shared state before every test so tests don't leak side effects into one another, and each it() expresses a single behavioral expectation in plain language. Jasmine spies (jasmine.createSpy() or spyOn()) let you replace real dependencies with fakes, track calls, and control return values without touching the network or the DOM—critical for keeping unit tests fast and deterministic.

🏏

Cricket analogy: A describe() naming the unit under test with a beforeEach() resetting shared state is like a fresh net session where the pitch is re-rolled before every batter faces a new bowler, and a Jasmine spy replacing a real dependency is like using a bowling machine set to a known speed instead of an unpredictable live bowler.

typescript
import { CalculatorService } from './calculator.service';

describe('CalculatorService', () => {
  let service: CalculatorService;

  beforeEach(() => {
    service = new CalculatorService();
  });

  it('should add two numbers correctly', () => {
    expect(service.add(2, 3)).toBe(5);
  });

  it('should throw when dividing by zero', () => {
    expect(() => service.divide(10, 0)).toThrowError('Division by zero');
  });

  it('should call the logger spy exactly once', () => {
    const logSpy = jasmine.createSpy('log');
    service.onResult = logSpy;
    service.add(1, 1);
    expect(logSpy).toHaveBeenCalledTimes(1);
    expect(logSpy).toHaveBeenCalledWith(2);
  });
});

Testing Services with Dependency Injection

Services that depend on other injectables are best tested through Angular's TestBed rather than by manual instantiation, because TestBed resolves the dependency graph the same way the real application does. TestBed.configureTestingModule() registers providers—often replacing a real HttpClient or a third-party SDK with a mock—and TestBed.inject() retrieves the configured instance. This keeps tests fast while still exercising Angular's DI resolution logic, catching wiring mistakes that a hand-instantiated object would never reveal.

🏏

Cricket analogy: Testing a service through TestBed instead of manual instantiation is like fielding a full training XI resolved through the actual selection process instead of hand-picking eleven random club players, catching wiring mistakes a scratch team would never reveal.

Karma requires a real browser engine, which is why CI pipelines typically install ChromeHeadless (via the Puppeteer or Karma-Chrome-Launcher packages) rather than a full desktop browser. Jest, by contrast, runs entirely in Node using jsdom to simulate the DOM, which is faster to start but doesn't execute in an actual browser rendering engine—a trade-off worth knowing when comparing Angular's default stack to tools used in React or Vue projects.

Forgetting to reset spies or shared mutable state between tests is one of the most common sources of flaky suites. Always initialize fixtures and spies inside beforeEach() rather than at the describe() level, so each test starts from a clean, predictable baseline.

Code Coverage and CI Integration

Running ng test --code-coverage produces an Istanbul-based coverage report showing which statements, branches, functions, and lines were exercised. Teams often enforce minimum coverage thresholds in karma.conf.js to prevent regressions. For continuous integration, ng test --watch=false --browsers=ChromeHeadless runs the suite once and exits with a non-zero code on failure, making it suitable for pipeline gating.

🏏

Cricket analogy: Running ng test --code-coverage for an Istanbul report is like a post-match analysis showing exactly which deliveries, shots, and fielding positions were actually tested during the innings, with teams enforcing a minimum coverage threshold like a board mandating every net session hit a fitness benchmark, and --watch=false --browsers=ChromeHeadless is like a scheduled fitness test run once with a pass/fail result for selection.

  • Jasmine provides the describe/it/expect syntax and matchers; Karma is the browser-based test runner that executes the compiled specs.
  • ng generate scaffolds a *.spec.ts file automatically for components, services, directives, and pipes.
  • Use spyOn() or jasmine.createSpy() to fake dependencies and verify interactions without hitting real network or DOM APIs.
  • TestBed.configureTestingModule() and TestBed.inject() resolve services through Angular's real dependency injection graph.
  • beforeEach() should reset fixtures and spies to avoid state leaking between tests and causing flakiness.
  • ng test --code-coverage generates an Istanbul report to track statement, branch, and line coverage over time.

Practice what you learned

Was this page helpful?

Topics covered

#TypeScript#AngularStudyNotes#WebDevelopment#UnitTestingWithJasmineAndKarma#Unit#Testing#Jasmine#Karma#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse