7

Metin girişi var ve değişiklikleri dinliyorum.Angular2 Bileşen: Test formu giriş değeri değişikliği

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> 

her şey iyi çalışır uygulamayı çalıştıran ama birim test bunun istiyorum.

Yani burada ben .search() yöntem çağrılmaz olarak test başarısız

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() 
     }) 
    }) 

çalıştığı şey budur.

value'u testin değişikliğin farkına varması için başka bir şekilde ayarlamalıyım ama gerçekten nasıl olduğunu bilmiyorum.

Herkesin fikri vardır?

cevap

18

O biraz geç olabilir, ama senin kod ayarı giriş elemanı değerden sonra input olayı gönderen olmadığını görünüyor:

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

Updating input html field from within an Angular 2 test

0

FormControl değeri değişmezse tetiklenmesi kadar basittir gibi:

cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue);