This tutorial aims to provide a thorough understanding of component testing in Angular. By the end of this tutorial, you will learn how to write and run comprehensive unit tests for Angular components.
Component testing is an essential part of the software development process, especially in Angular applications. Component tests ensure that individual components (like buttons, input fields, etc.) function as expected.
In Angular, we usually write unit tests in a separate .spec.ts file. We use the describe function to group related tests, and it function to define a single test.
You can run the tests using the Angular CLI command ng test.
Let's write a test for a button component.
// button.component.spec.ts
import { ButtonComponent } from './button.component';
describe('ButtonComponent', () => {
let component: ButtonComponent;
beforeEach(() => {
component = new ButtonComponent();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
In this code, we're creating an instance of ButtonComponent and then checking if it's created successfully.
// input.component.spec.ts
import { InputComponent } from './input.component';
describe('InputComponent', () => {
let component: InputComponent;
beforeEach(() => {
component = new InputComponent();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should emit valueChange event on input change', () => {
spyOn(component.valueChange, 'emit');
const value = 'New Input Value';
component.onChange(value);
expect(component.valueChange.emit).toHaveBeenCalledWith(value);
});
});
This test checks whether the valueChange event is correctly emitting the new input value when the onChange method is called.
In this tutorial, you learned the basics of component testing in Angular, wrote unit tests for Angular components, and ran tests using Angular CLI.
Keep practicing to master these concepts. You can also explore Angular's documentation for more details.
CheckboxComponent that checks whether a valueChange event is emitted when the checkbox state changes.ListComponent that checks whether the correct number of items are rendered when the items input prop changes.Remember to follow the Arrange-Act-Assert pattern, and isolate each test. Happy testing!