14

I want to be able to simulate a user typing into a text box using reactjs so that I can test my validation status messages.

I have a react component which validates on keyUp

Below is a simple example of what I've tried.

nameInput.props.value = 'a';
React.addons.TestUtils.Simulate.keyUp(nameInput);
React.addons.TestUtils.findRenderedDOMComponentWithClass(component, 'has-error');

This doesn't seem to change the value of the bound textbox when I debug in the validator

React.addons.TestUtils.Simulate.keyUp(nameInput, {key: 'a'});
React.addons.TestUtils.findRenderedDOMComponentWithClass(component, 'has-error');

This doesn't either.

Could someone point me on the right track, the second is inline with the documentation I could find around simulate (http://facebook.github.io/react/docs/test-utils.html), the first makes sense to me (set the actual textbox value then fake an event)

pgSystemTester
  • 8,979
  • 2
  • 23
  • 49
undefined
  • 33,537
  • 22
  • 129
  • 198

2 Answers2

26

By setting nameInput.props.value = 'a'; you are not actually updating the value in your component.

You should use React.addons.TestUtils.Simulate.change(nameInput, { target: { value: 'a' } }); or something similar to simulate modifying the actual value.

jonowzz
  • 425
  • 5
  • 8
  • 3
    Is there more a comprehensive documentation on Simulate? I could only find a few examples and I would like to know more about the "specifications". Why "target", why "value"? What other options are available? – diogovk Dec 09 '14 at 22:23
  • 1
    I only know about this page off hand: http://facebook.github.io/react/docs/test-utils.html. Other than that I'm pretty sure it simply follows the native values that get changed when events are fired off in the browser. – jonowzz Dec 09 '14 at 22:37
  • 1
    And where would I find the documentation of those native values? – diogovk Dec 10 '14 at 10:56
  • 2
    The MDN reference page for events is probably a good place to look as the page for each event covers some of the details of what values change: https://developer.mozilla.org/en-US/docs/Web/Events. Other than that you could also possibly look at the W3 spec: http://www.w3.org/TR/DOM-Level-2-Events/events.html. – jonowzz Dec 10 '14 at 20:56
1

I found that this syntax works better for me:

  const emailInput = component.refs.userEmailInput;
  emailInput.value = 'test@gmail.com';
  Simulate.change(component.refs.userEmailInput);

The second line updates the input with the text, 'test@gmail.com'. The last line triggers the change.

Matt Goo
  • 1,118
  • 1
  • 11
  • 12