Unit testing in Angular involves testing individual components, services, and other units of code in isolation to ensure they work correctly. Angular provides the TestBed and various testing utilities to facilitate unit testing. Here's an example to demonstrate unit testing in Angular:
Let's consider a simple component called `CalculatorComponent` that performs basic arithmetic operations:
import { Component } from '@angular/core';
@Component({
selector: 'app-calculator',
template: `
<div>
<input type="number" [(ngmodel)]="num1">
<input type="number" [(ngmodel)]="num2">
<button (click)="add()">Add</button>
<p>Result: {{ result }}</p>
</div>
`
})
export class CalculatorComponent {
num1: number;
num2: number;
result: number;
add() {
this.result = this.num1 + this.num2;
}
}
To write unit tests for this component, we can utilize the testing framework provided by Angular. Here's an example test using the Jasmine testing framework:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CalculatorComponent } from './calculator.component';
describe('CalculatorComponent', () => {
let component: CalculatorComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ CalculatorComponent ]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(CalculatorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should add two numbers', () => {
component.num1 = 5;
component.num2 = 10;
component.add();
expect(component.result).toBe(15);
});
});
In the test above, we use the
`describe` function to define a test suite for the
`CalculatorComponent`. Inside the
`beforeEach` function, we create an instance of the component using
`TestBed.createComponent` and assign it to `fixture`. We then assign the component instance to `component` for easy access within the tests.
The
`it` function defines an individual test case. In this case, we set `num1` and `num2` to 5 and 10, respectively, call the `add` method, and expect the `result` to be 15.
To run the unit tests, you can use Angular's CLI command
`ng test`, which executes the tests using Karma test runner.
Conclusion :
By writing
unit tests, you can ensure that individual components, services, and other units of code behave as expected, helping you catch bugs early and maintain code quality in your Angular application.