7

テキスト入力があり、変更を待ち受けています。Angular2コンポーネント:テストフォーム入力値の変更

mycomponent.ts

ngOnInit() { 
    this.searchInput = new Control(); 
    this.searchInput.valueChanges 
     .distinctUntilChanged() 
     .subscribe(newValue => this.search(newValue)) 
} 
search(query) { 
    // do something to search 
} 

mycomponent.html

<search-box> 
    <input type="text" [ngFormControl]="searchInput" > 
</search-box> 

すべてが正常に動作するアプリケーションを実行している、しかし、私はユニットテスト、それにしたいです。

だからここで私は.search()メソッドが呼び出されないように、テストが失敗した

mycomponent.spec.ts

beforeEach(done => { 
    createComponent().then(fix => { 
     cmpFixture = fix 
     mockResponse() 
     instance = cmpFixture.componentInstance 
     cmpFixture.detectChanges(); 
     done(); 
    }) 
}) 
describe('on searching on the list',() => { 
     let compiled, input 
     beforeEach(() => { 
      cmpFixture.detectChanges(); 
      compiled = cmpFixture.debugElement.nativeElement; 
      spyOn(instance, 'search').and.callThrough() 
      input = compiled.querySelector('search-box > input') 
      input.value = 'fake-search-query' 
      cmpFixture.detectChanges(); 
     }) 
     it('should call the .search() method',() => { 
      expect(instance.search).toHaveBeenCalled() 
     }) 
    }) 

を試みたものです。

私はvalueをテストの変更を実現する別の方法で設定しなければならないと思いますが、実際にはわかりません。

誰でもアイデアがありますか?

答えて

18

それは少し遅れるかもしれませんが、それはあなたのコードが入力された要素の値を設定した後inputイベントをディスパッチされていないようです:FormControlの値の変更をトリガ

// ...  
input.value = 'fake-search-query'; 
input.dispatchEvent(new Event('input')); 
cmpFixture.detectChanges(); 
// ... 

Updating input html field from within an Angular 2 test

0

は同じくらい簡単ですとして:

cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue); 
関連する問題