Unit Testing Jasmine & Karma
Writing your first test case in Angular helps ensure that your components and services work as expected. Angular typically uses Jasmine for writing tests and Karma as the default test runner. In this topic, you will create and understand a simple unit test for an Angular service.
describe(), it(), and expect().it() to set up a fresh test state.A basic Jasmine test in Angular is organized as:
// Basic Jasmine test structure
describe('MyFeature', () => {
it('should do something', () => {
expect(true).toBeTrue();
});
});
Inside a real Angular test, you usually configure the testing environment using TestBed, create or inject the service/component, and then write expectations using expect().
Let’s create a simple GreetingService with a method that returns a greeting and then write tests for it.
// greeting.service.ts - simple service that returns a greeting
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GreetingService {
getGreeting(name: string): string {
return `Hello, ${name}!`;
}
}
// greeting.service.spec.ts - tests for GreetingService
import { TestBed } from '@angular/core/testing';
import { GreetingService } from './greeting.service';
describe('GreetingService', () => {
let service: GreetingService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(GreetingService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should return correct greeting', () => {
const greeting = service.getGreeting('Angular');
expect(greeting).toBe('Hello, Angular!');
});
});
ng test from the Angular project root.*.spec.ts files using Jasmine.TestBed creates a testing module and injects GreetingService before each test."should be created" checks that the service instance exists.getGreeting('Angular') and expects the string "Hello, Angular!".describe() and it() blocks to make debugging easier.beforeEach().FarewellService with a method getFarewell(name: string) that returns "Goodbye, <name>!". Write tests to ensure it returns the correct farewell.@Input() property (for example, title) and write a test that verifies the input value is rendered in the template.GreetingService that checks behavior when an empty name is passed (e.g., return a default greeting).