2017-06-22 20 views
3

我有以下功能進行單元測試。我在元件中使用了帶有查看子元件的文本框元素,並且在測試中,我需要在調用setTimeout()之後測試我的文本框是否被聚焦。如何檢查我的元素是否集中在角度4的單元測試中?

@ViewChild('searchInput') searchInput: ElementRef; 
function A(show) { 
     const self = this; 
     if (show) { 
      this.xyz= true; 
      setTimeout(function() { 
       self.searchInput.nativeElement.focus(); 
      }, 0); 
     } else { 
      self.xyz= false; 
      self.abc = ''; 
     } 
    } 

這裏是我想我的測試案例:

it('textbox get focus toggleSearch', async(() => { 
     let el: DebugElement; 

     component.toggleSearch(true); 
     el = fixture.debugElement.query(By.css('#search-input-theme')); 
     let native: HTMLElement = el.nativeElement; 
     spyOn(native,'focus'); 
     fixture.whenStable().then(() => { 
      expect(native.focus).toHaveBeenCalled(); 
     }); 
    })); 
+0

您的規格文件在哪裏? –

+0

代碼已更新@AmitChigadani – Pranjal

回答

2

也許是這樣的:

const input = de.query(By.css("your_field_selector")).nativeElement; 
const focusElement = de.query(By.css(":focus")).nativeElement; 
expect(focusElement).toBe(nomeInput); 

路易斯

0

路易斯·阿布雷烏的回答爲我工作的,不僅我想窺探調焦方法,但重點是放在視圖的正確元素上。以下是一個示例:

describe('Email input focus',() => { 
    beforeEach(() => { 
    spyOn(comp.emailField.nativeElement, 'focus'); 
    comp.ngAfterViewInit(); 
    }); 

    it('Should call the focus event',() => { 
    expect(comp.emailField.nativeElement.focus).toHaveBeenCalled(); 
    }); 

    it('Should be focused on the view',() => { 
    fixture.detectChanges(); 
    const emailInput = de.query(By.css('#email')).nativeElement; 
    const focusedElement = de.query(By.css(':focus')).nativeElement; 
    expect(focusedElement).toBe(emailInput); 
    }); 
}); 
相關問題