How to write unit test for your Angular App
Muhammad Awais
Software/Ai Technologist ?? | Internationally Recognised Lead Software Engineer | Speaker | Author x2 | Mentor | OpenSource Contributor
Certainly! Writing unit tests in Angular involves using tools like Jasmine, TestBed, and other testing utilities provided by Angular. Let's walk through the process of creating a simple unit test for an Angular service step by step.
For this example, let's assume you have a service named MathService that provides basic math operations.
Step 1: Create the Service Create a file named math.service.ts for your service implementation.
// math.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MathService {
add(a: number, b: number): number {
return a + b;
}
}
Step 2: Create the Test Create a file named math.service.spec.ts in the same directory to write your unit test.
// math.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { MathService } from './math.service';
describe('MathService', () => {
let service: MathService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MathService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should add two numbers correctly', () => {
const result = service.add(2, 3);
expect(result).toBe(5);
});
});
Step by Step Explanation:
领英推荐
Step 3: Run the Test To run the test, you typically use the Angular CLI's testing commands. Open your terminal and navigate to your project directory:
ng test
This command will initiate the test runner, and it will execute the tests in the files ending with .spec.ts. If everything is set up correctly, you should see the test results in your terminal.
That's it! This is a basic example of writing and running unit tests for an Angular service using Jasmine and TestBed.