2017-02-28 58 views
3

我似乎無法測試綁定到Angluar2模型的輸入框。我對此有點新,所以請和我一起裸照。Angular 2測試輸入框綁定

我有一個非常基本的Angular2組件,它包含一個綁定到模型的inputbox。

<form> 
    <input type="text" [(ngModel)]="searchTerm" name="termsearchTerm" (keyup)="search()" value=""/> 
</form> 

這裏是後面的代碼:

import { Component, Input, Output, EventEmitter } from '@angular/core'; 

@Component({ 
    moduleId: module.id, 
    selector: 'sc-search', 
    templateUrl: 'search.component.html' 
}) 

export class SearchComponent { 
    @Input() data: any; 
    @Output() onSearchTermChanged = new EventEmitter<string>(); 
    private searchTerm: string; 

    search() { 
     this.onSearchTermChanged.emit(this.searchTerm); 
    } 
} 

當運行下面的測試繼續得到預期的不確定等於「約翰」。 我期待測試通過。

searchableHierarchyComponentFixture.detectChanges(); 

    let termInputDbg = searchableHierarchyComponentFixture.debugElement.query(By.css('input[name="termsearchTerm"]')); 
    let input = searchableHierarchyComponentFixture.nativeElement.querySelector('input'); 

    input.value = 'John'; 

    let evt = document.createEvent('Event'); 
    evt.initEvent('keyup', true, false); 

    termInputDbg.triggerEventHandler('keyup', null); 
    input.dispatchEvent(evt); 


    tick(50); 
    searchableHierarchyComponentFixture.detectChanges(); 
    searchableHierarchyComponentFixture.whenStable(); 
    expect(searchableHierarchyComponentFixture.componentInstance.searchTerm).toEqual('John'); 

回答

3

那麼幾件事情:

  1. 你需要調用tick創建組件後。不完全確定,但我認爲模型綁定是異步發生的。沒有滴答作響,測試將失敗。
  2. 該指令監聽input事件,而不是keyup。當input事件發生時,指令更新綁定。

下面是一個完整的測試(也Plunker

import { Component } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { TestBed, fakeAsync, tick } from '@angular/core/testing'; 
import { By } from '@angular/platform-browser'; 

@Component({ 
    selector: 'test', 
    template: ` 
    <form> 
     <input type="text" [(ngModel)]="query" name="query" /> 
    </form> 
    ` 
}) 
class TestComponent { 
    query: string; 
} 

describe('TestComponent: ngModel',() => { 

    let fixture; 
    let component; 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     imports: [FormsModule], 
     declarations: [TestComponent] 
    }); 
    fixture = TestBed.createComponent(TestComponent); 
    component = fixture.componentInstance; 
    }); 

    it('should change the value', fakeAsync(() => { 
    let input = fixture.debugElement.query(By.css('input')).nativeElement; 

    fixture.detectChanges(); 
    tick(); 

    expect(component.query).toBeFalsy(); 

    input.value = 'Hello World'; 
    input.dispatchEvent(new Event('input')); 
    tick(); 

    expect(component.query).toBe('Hello World'); 

    })); 
}); 

參見

+0

夢幻般的答案。謝謝! –

+0

'tick()'和'input.dispatchEvent'技巧挽救了我的生命! – elli0t

+0

嘿傢伙,就像一個答案和問題本身。但是這裏的tick函數是什麼?我現在有同樣的情況。並且想要測試綁定到輸入的ngModel。我需要那個tick()嗎? –