Can't Test Submit Handler In React Component
I'm trying to test events for my component and I the submit handler isn't being called. All my unit tests are working except for the events. I'm using Tape, Sinon and JSDOM and have looked around a lot online to find anyone with a similar issue. There is a Github issue for a similar problem, I'm not 100% sure if it's exactly the same though. https://github.com/facebook/react/issues/1185 There is also a related post here on SO but it didn't help as they're using shallow rendering.
Test:
// Create a document using JSDOM
const document = createDocument();
let output;
const onSubmitHandler = spy();
// Render the DOM
output = renderDOM(
<ToDoCreate
onSubmit={onSubmitHandler}
/>,
document.body);
const form = TestUtils.findRenderedDOMComponentWithTag(output, 'form');
// Simulate a submit
TestUtils.Simulate.submit(form);
const actual = onSubmitHandler.callCount;
const expected = 1;
// Test the event handler was called
assert.equal(actual, expected);
assert.end();
Result:
# ToDoCreate component
# ...submitted form to create a ToDo
not ok 14 should be equal
---
operator: equal
expected: 1
actual: 0
...
Does anyone have any ideas on why this wouldn't be working?
Thanks
Update: Adding the ToDoCreate's render() output
<form className={toDoCreateClasses} onSubmit={this._handleToDoCreateSubmit}>
<div className="form-group">
<label className="sr-only">New ToDo</label>
<input type="text" className="form-control ToDoInput" ref="title" placeholder="Add a new ToDo..." />
</div>
<button type="submit" className="btn btn-primary">Add</button>
</form>
Update: Adding the _handleToDoCreateSubmit method
_handleToDoCreateSubmit(e) {
e.preventDefault();
// Get the ToDo title
let title = this.refs.title.value;
// Validate
if ( title === '' ) {
window.alert('You need to enter a ToDo first :)');
return false;
}
// Trigger the submit event
ToDoDispatcher.dispatch({
actionType: 'TODO_CREATE_SUBMIT',
title: title
});
// Clear the Dom node
this.refs.title.value = '';
}
Answer
@GilesB thanks to you, I had should ask before responding. adding rounded bracket has worked for me:
// Render the DOM
output = renderDOM(
<ToDoCreate
onSubmit={onSubmitHandler()}
/>,
document.body);
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM