Can't test submit handler in React component

- 1 answer

Ad

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 = '';
}
Ad

Answer

Ad

@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);
Ad
source: stackoverflow.com
Ad