我正在測試傳遞給子組件的回調是在點擊子組件中的按鈕後調用的。我使用.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上。
而在我的github它是在Notetaker回購。 –