Testing Forms
Learn how to test different components of Angular forms.
We'll cover the following...
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:
Press + to interact
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)}}}
...