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

関連する問題