2016-06-08 70 views
7

任何人都可以幫助我測試酶中的input.focus()。我正在寫劇本與react.My代碼如下。在酶中測試input.focus()

public inputBox: any; 

componentDidUpdate =() => { 
    setTimeout(() => { 
     this.inputBox.focus(); 
    }, 200); 
} 

render() { 
    return (
     <div> 
      <input 
       type = 'number' 
       ref = {element => this.inputBox = element } /> 
     </div> 
    ); 
} 

回答

2

其他方法是測試元素是否獲得焦點,即在節點元素上調用focus()。爲了實現這個重點元素,需要通過ref標籤進行引用,就像它在您的示例中發生的那樣 - 引用被分配到this.inputBox。考慮下面的例子:

const wrapper = mount(<FocusingInput />); 
const element = wrapper.instance().inputBox; // This is your input ref 

spyOn(element, 'focus'); 

wrapper.simulate('mouseEnter', eventStub()); 

setTimeout(() => expect(element.focus).toHaveBeenCalled(), 250); 

此示例使用茉莉花spyOn,但你可以在任何間諜你喜歡。

+0

'eventStub()'從哪裏來? –

+1

'eventStub'是任何能夠讓你的測試通過的東西。在這個例子中,你可以假定組件'FocusingInput'正在監聽'mouseEnter'事件,並且當這個事件被觸發時('wrapper.simulate('mouseEnter',...)'這麼做)事件處理器可以對事件執行一些操作像'preventDefault'。爲了使這個工作,你需要準備事件存根來處理這個操作,併發送這個存根作爲'simulate'的第二個參數。以下是我的[活動存根](https://gist.github.com/mckomo/128bdb43434749ca1a2299d456ed7d7c)的示例。 – mckomo

13

您可以使用mount代替淺。 然後你可以比較document.activeElement和輸入的DOM節點是否相等。

const output = mount(<MyFocusingComponent/>); 

assert(output.find('input').node === document.activeElement); 

有關更多詳細信息,請參見https://github.com/airbnb/enzyme/issues/316

+1

爲我工作。爲了清楚起見,需要全局的'window'和'document'對象來掛載工作。爲了這個目的,我在第一個'describe'之前使用了下面的代碼:'從jsdom'導入jsdom; const doc = jsdom.jsdom('<!doctype html>'); global.document = doc; global.window = doc.defaultView;' – Ejaz

+0

對於Jest,請確保在CLI中設置了'--env = jsdom',或者在jest config中設置了''testEnvironment「:」jsdom「',那麼您不需要導入它 – WickyNilliams