7

मेरे पास एक टेक्स्ट इनपुट है और मैं परिवर्तनों को सुन रहा हूं।कोणीय 2 घटक: परीक्षण फ़ॉर्म इनपुट मूल्य परिवर्तन

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> 

आवेदन सब कुछ ठीक काम करता है चल रहा है, लेकिन मैं इकाई परीक्षण यह करना चाहते हैं।

तो यहाँ मैं क्या करने की कोशिश की

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

टेस्ट में विफल रहता है के रूप में .search() विधि नहीं बुलाया जाता है।

मुझे लगता है कि मुझे बदलाव के परीक्षण का एहसास करने के लिए value को एक और तरीके से सेट करना है, लेकिन मुझे वास्तव में नहीं पता कि कैसे।

किसी के पास विचार हैं?

उत्तर

18

यह एक छोटा सा देर से हो सकता है, लेकिन यह है कि अपने कोड की स्थापना इनपुट तत्व मूल्य के बाद input घटना भेजने नहीं है लगता है:

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

Updating input html field from within an Angular 2 test

0

FormControl का मूल्य परिवर्तन ट्रिगर के रूप में सरल है के रूप में:

cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue); 
संबंधित मुद्दे