2017-09-13 94 views
1

我正在測試傳遞給子組件的回調是在點擊子組件中的按鈕後調用的。我使用.simulate('click')函數來模擬react-bootstrap按鈕<Button></Button>React-jest-enzyme:在調用回調之前先測試調用另一個函數的子組件的回調

問題是我的按鈕的onClick()函數調用另一個函數update(),該函數調用傳遞給我的子組件的handleSave回調函數。 <FormControl/>元素的onKeyPress函數也調用我的組件的更新函數。這裏是我有我的孩子的組件設定:

update(event) {    

     //Have to check to see if the key stroke is the enter key or if it comes from the button click. 
     if(event.charCode === 13 || event.type === 'react-click'){ 

     // Have to use this get the ref value because this.refs.input.value doesn't work. 
     var input = ReactDOM.findDOMNode(this.refs.input); 

     input.value = ''; 
     this.props.handleSave(); 
    } 
} 

render(){ 

    return( 
     <Form> 
     <FormControl type="text" ref="input" onKeyPress={this.update.bind(this)} placeholder="Enter Note" /> 
     <Button onClick={this.update.bind(this)}>Submit </Button> 
     </Form> 
    ) 
} 

那就是爲什麼我update()功能有檢查,看是否從charCode==13來了,這是中charCode爲回車鍵,或按一下按鈕,因爲這兩個保存信息是在<FormControl />

我有我的測試設置是這樣的:

describe('Input',() => { 

const mockHandleText = jest.fn(); 
const mockHandleSave = jest.fn(); 
const props   = {handleSave: mockHandleSave} 
let input   = shallow(<Input {...props} />); 

    describe('when entering a note',() => { 

    beforeEach(() => { 
      input.find('Button').simulate('click', { 
       charCode: 13 
      }); 
    }); 


    it('adds the note to state',() => { 
     expect(props.handleSave).toHaveBeenCalled(); 
    }); 
    }); 
}); 

一個奇怪的事情是,我要傳遞一個對象作爲第二個參數爲.simulate()功能因爲如果我不它會給我一個錯誤說無法讀取的不確定則charCode但是當傳遞一個對象,該對象甚至不必有一個事件屬性,那麼它只是說

expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called.

另外如果我沒有傳入一些屬性的對象,那麼它也打破了我的另一個測試,我有一個回調我的元素的onChange函數。爲了簡單起見,我將其從代碼示例中刪除了,並且只是上傳了代碼給我帶來了問題。我也在使用引導形式。完整的代碼在我的github上github.com/Alebron23上。

+0

而在我的github它是在Notetaker回購。 –

回答

0

酶的淺層方法不會渲染整個DOM樹,只是最淺層次。您將無法找到使用它的嵌套子項。在淺層文檔(https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md)中,他們討論如果您需要在子組件上聲明任何行爲,則必須使用shallow()以外的內容。

你的其他選擇,其一是利用渲染(),或相當可能更多,因爲渲染()是靜態的,你想測試方面效果 - 完全安裝() 成分(https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md)來代替。

+0

沒有,當我試圖使用安裝而不是淺的工作。我仍然有同樣的錯誤。但是我在onClick函數中調用組件的函數仍然是組件的一部分,所以它應該仍然可以調用,因爲shallow允許您將組件作爲一個單元進行測試。 –

+0

並感謝您的快速回復。 –

相關問題