Search⌘ K

Testing Forms

Explore how to test reactive forms in Angular by writing unit tests that verify form control values, button states, and submit events. Understand how to trigger DOM events and use test utilities for efficient form validation in your applications.

We will learn how to test Angular forms. Previously, we learned that forms are an integral part of an Angular application. It is rare for an Angular application not to at least have a simple form, such as a search form. We have already learned that reactive forms are better than template-driven forms in many ways and are easier to test. So, in this section, we will focus on only testing reactive forms.

Testing the form input

Consider the following search.component.ts file:

TypeScript 4.9.5
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-search',
template: `
<form [formGroup]="searchForm" (ngSubmit)="search()">
<input type="text" placeholder="Username" formControlName="searchText">
<button type="submit" [disabled]="searchForm.invalid">Search</
button>
</form>
`
})
export class SearchComponent {
get searchText() {
return this.searchForm.controls.searchText;
}
searchForm = new FormGroup({
searchText: new FormControl('', Validators.required)
});
search() {
if(this.searchForm.valid) {
console.log('You searched for: ' + this.searchText.value)
}
}
}

In the preceding component, we can write our unit tests to verify that: ...