{

Angular component testing - Input text value with test case examples


In this tutorial, How to unit test input text control on UI form in Angular application.

In my previous post, Already discussed about how to read input text value in Angular application.

I have existing application created using ng new cli command.

Let’s create Angular component using ng g c component command. This creates an angular component.

Let’s add input text field and button binding to the template and typescript component.

In this component, We have a input type text and button On clicking the button, Displayed the entered value. The value of the input box is binding using two way binding syntax - [(ngModel)]

Here is an Angular template component - input-text.component.html

<p>input-text works!</p>
<p><input type="text" id="username" name="username" [(ngModel)]="username"></p>
<h1> {{username}}</h1>

<button type="button" (click)="clickme()">Clickme</button>

In typescript component, Declare two way binding variable in input-text.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-input-text',
  templateUrl: './input-text.component.html',
  styleUrls: ['./input-text.component.scss']
})
export class InputTextComponent implements OnInit {

  constructor() { }
  username: string = '';
  clickme() {
    console.log('it does nothing', this.username);
  }

  ngOnInit(): void {
  }

}

Let’s write a angular component unit testing for this input text box

Angular unit testing input text component

By default angular cli generates default spec files with following lines of code Here are steps

  • TestBed provides an angular environment for test components.
  • Default TestBed is configured with testing module with components,directives and services, finally compile component using compileComponents method.
  • Create a component using createComponent method which returns the ComponentFixture
  • ComponentFixture is an wrapper component around user component
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { InputTextComponent } from './input-text.component';

describe('InputTextComponent', () => {
  let component: InputTextComponent;
  let fixture: ComponentFixture<InputTextComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [InputTextComponent]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(InputTextComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();

  });

How to test label of an input text in Angular component.

This is an test case for checking for

  • label exists or not
  • Label name contains text is Enter username value

Here are steps

  • First, label is queried using debugElement.query

  • From a given ComponentFixture, We have a debugElement to access DOM elements.

  • query method returns child elements using css selectors.

  • It returns label element

  • Assert label exists and outerText contains give text.

    Here is an test case for

  it('should check input label name', () => {
    let queryByLabel = fixture.debugElement.query(By.css("label[for=username]"));
    expect(queryByLabel).toBeTruthy();
    expect(queryByLabel.nativeElement).toBeTruthy();
    expect(queryByLabel.nativeElement.outerText).toContain("Enter username");

  })

Angular Unit testing for set and read input text values

Let’s write a unit test cases for setting input text value.

  • First retrieve input element usingBy.css with id selector
  • Set the value of the input box using nativeElement method
  • Once value is set, Dispatch an input event using dispatchEvent method
  • Finally detectChanges using manual detection in Angular to update DOM object.
  • const username = fixture.debugElement.query(By.css('#username')); username.nativeElement.value = ‘john’; username.nativeElement.dispatchEvent(new Event(‘input’)); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); console.log(‘sendInput : ‘, username.nativeElement.value); expect(username.nativeElement.value).toContain(‘john’); }); });
    
    ## Submit button to read input text and validate value
    
    This test cases covers an setting input value and do button click and validates the input text value
    
    -  Get button and input using testing query element
    -  Change input value and issue Input event
    -  manually trigger click event on button
    -  manually reload component using detectChanges
    -  Finally assert input value with displayed value
    
    

Here is an example code

  it('Form submit click ', async () => {
    const submitButton = fixture.debugElement.query(By.css('#submit'));
    const username = fixture.debugElement.query(By.css('#username'));
    username.nativeElement.value = 'asdf';
    username.nativeElement.dispatchEvent(new Event('input'));

    submitButton.triggerEventHandler('click', null);

    const displayText = fixture.debugElement.query(
      By.css('h1')
    );
    // manual detection 
    fixture.detectChanges();
    expect(displayText.nativeElement.textContent).toBe('asdf');


  });

Conclusion

You learned angular component testing for following things

  • change and read input text value
  • input label testing on form
  • Button submit for input text form
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.