Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a test case for input changes in Angular

Hi I am developing an application using Angular and TypeScript.

Following is the template code:

<input type="text" placeholder="Search Results" (input)="searchInput($event)">

and my typescript code regarding searchInput method is :

searchInput(event: Event & { target: HTMLInputElement}) {
   const { value } = event.target;
   this.value = value;
    // calling other method to reset values
  }

I was wondering the how to write input test cases in my spec.ts file.

describe('Component', () => {
  let component: Component;
  let fixture: ComponentFixture<Component>;
  const event = Event; // Is this fine ?
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
          AppModule
      ],
      providers: [
      ]
    })
    .compileComponents();
  }));

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

  it('searchInput() ', () => {
    // how to approach 
  });
});

Please provide a way how I will approach for writing test cases.

like image 892
Vaibhav Avatar asked Jun 20 '17 06:06

Vaibhav


People also ask

Can you conduct automated testing on Angular?

The Angular framework is a mature and comprehensive solution for enterprise-ready applications based on web technologies. At Angular's core lies the ability to test all application parts in an automated way.


1 Answers

Here is one way of writing a simple test case.

What it does:

  1. Creates the component
  2. Checks that the default value for value is falsy
  3. Finds the HTML input element by CSS (you might need to be more specific here, depending on your template)
  4. Set's the value of the input element and dispatches an input event
  5. Makes sure that the value of value has been updated correctly

Code (remember to import By):

...    

import { By } from '@angular/platform-browser';

...

it('searchInput should update value when input changes', async(() => {
    const fixture = TestBed.createComponent(AppComponent);

    expect(fixture.debugElement.nativeElement.value).toBeFalsy()

    const el: HTMLInputElement = fixture.debugElement.query(By.css('input')).nativeElement;
    const testValue = 'some_value';

    el.value = testValue;
    el.dispatchEvent(new Event('input'));

    expect(fixture.componentInstance.value).toEqual(testValue);
}));
like image 124
Fredrik Lundin Avatar answered Oct 22 '22 15:10

Fredrik Lundin