Unit Testing With Karma/Jest

Test a Service in Isolation

Unit Testing With Karma/Jest

Angular ships with Karma + Jasmine; many projects swap in Jest. Either way, services test like plain TypeScript with a little help from TestBed.

4 min read Level 2/5 #angular#testing#jasmine
What you'll learn
  • Run ng test to launch the runner
  • Use TestBed.inject to grab a service instance
  • Mock HTTP with HttpTestingController

ng new wires up Karma + Jasmine for you, and ng test runs the suite in a real browser. Many teams swap in Jest for speed — the test code itself barely changes.

Run the Test Runner

ng test
# launches Karma, opens a Chrome instance, watches for changes

Files ending in .spec.ts are picked up automatically. The CLI generates one next to every component, service, and pipe you scaffold.

Test a Service

Services are usually the easiest thing to test — they’re plain classes with injected dependencies.

import { TestBed } from '@angular/core/testing';
import { UsersService } from './users.service';

describe('UsersService', () => {
  let svc: UsersService;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers: [UsersService] });
    svc = TestBed.inject(UsersService);
  });

  it('starts empty', () => {
    expect(svc.users().length).toBe(0);
  });
});

TestBed is a mini DI container. configureTestingModule registers providers; inject pulls instances out.

Mock HTTP With HttpTestingController

When a service makes HTTP calls, don’t hit the real network — use provideHttpClientTesting and assert on the requests.

import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [provideHttpClient(), provideHttpClientTesting()],
  });
});

it('fetches users', () => {
  const http = TestBed.inject(HttpTestingController);
  const svc = TestBed.inject(UsersService);

  svc.list().subscribe(users => expect(users.length).toBe(2));

  const req = http.expectOne('/api/users');
  req.flush([{ id: 1 }, { id: 2 }]);
  http.verify();
});

expectOne asserts exactly one request was made; flush returns a fake response.

Component Testing →