mardi 27 septembre 2016

Angular 2: Testing [(ngModel)] two way data binding

I am trying to test the two way data binding of ngModel with the following code, but when I am running my test I always get: Expected '' to be 'test@wikitude.com', 'searchQuery property changes after text input'. Maybe it has something to do with the searchField.dispatchEvent part, but so far I couldn't figure out why the test is not changing the textContent of my displayField. The project was built with angular-cli": "1.0.0-beta.15. I tried to follow this guide but so far had no luck. Would be nice if you could help me make my test pass.

This is my component:

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

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
  searchQuery: string;
  active: boolean = false;

  onSubmit(): void {
    this.active = true;
  }
}

This is my component template:

<input id="name" [(ngModel)]="searchQuery" placeholder="customer">
<h2><span></span></h2>

And here are is my spec:

/* tslint:disable:no-unused-variable */

import {TestBed, async, ComponentFixture, tick} from '@angular/core/testing';
import { SearchComponent } from './search.component';
import {CommonModule} from "@angular/common";
import {FormsModule} from "@angular/forms";
import {By} from "@angular/platform-browser";

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

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [SearchComponent],
      imports: [
        CommonModule,
        FormsModule
      ]
    });

    fixture = TestBed.createComponent(SearchComponent);
    component = fixture.componentInstance;
  });

  it('should bind the search input to the searchQuery variable', () => {   
    const searchInputText: string = 'test@wikitude.com';
    const searchField: HTMLInputElement = fixture.debugElement.query(By.css('input')).nativeElement;
    const displayField: HTMLElement = fixture.debugElement.query(By.css('span')).nativeElement;

    searchField.value = searchInputText;

    searchField.dispatchEvent(new Event('input'));

    fixture.detectChanges();

    expect(displayField.textContent).toBe(searchInputText, 'searchQuery property changes after text input');
  });
});

Aucun commentaire:

Enregistrer un commentaire