2017-04-03 228 views
1

我正在尝试测试Angular 2中的双向绑定功能。我也通读了其他一些答案,但仍然无法通过测试。Angular NgModel双向绑定单元测试

当输入字段更新时,我想运行一个测试,确保AppComponent类的searchQuery属性与输入字段的值相同。

如前所述,我已经阅读了其他一些答案,因为我已经包含了额外的代码片断。那么目前可能不需要什么呢?

组件

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

@Component({ 
    selector: 'app-root', 
    template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">', 
    styles: [''] 
}) 
export class AppComponent { 
    public searchQuery: string; 

    onChange() { 
     console.log(this.searchQuery); 
    } 

} 

单元测试

import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing'; 
import { By } from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 

import { AppComponent } from './app.component'; 
import { FormsModule } from '@angular/forms'; 

describe('AppComponent',() => { 
    let comp: AppComponent; 
    let fixture: ComponentFixture<AppComponent>; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ AppComponent ], 
     providers: [], 
     imports: [ FormsModule ], 
     schemas: [] 
    }) 
    .compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(AppComponent); 
    comp = fixture.componentInstance; 
    }); 

    it('should create the app', fakeAsync(() => { 
    const de = fixture.debugElement.query(By.css("#search")); 
    const el = de.nativeElement; 

    el.value = "My string"; 

    var event = new Event('input', { 
     'bubbles': true, 
     'cancelable': true 
    }); 
    el.dispatchEvent(event); 

    tick(); 

    fixture.detectChanges(); 

    expect(comp.searchQuery).toEqual("My string"); 
    })); 
}); 

如果有更好的方法,我当然高兴来解决这个问题的任何反馈。

回答

2

你有调度事件之前运行

fixture.detectChanges(); 

,以确保您的控制已初始化并注册onChange事件

setUpControl功能

// view -> model 
dir.valueAccessor.registerOnChange(function (newValue) { 
    dir.viewToModelUpdate(newValue); 
    control.markAsDirty(); 
    control.setValue(newValue, { emitModelToViewChange: false }); 
}); 

Plunker Example

又见

+0

非常感谢,yurzui!一如既往地赞赏。并感谢Plunker的例子。 – bmd

+0

不客气! – yurzui