Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating text entry with reactJs TestUtils

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)

like image 486
Not loved Avatar asked Jul 14 '14 05:07

Not loved


People also ask

How can you simulate clicking on an element using React JS testing utilities?

Simulate a Click Event The onClick should pass through to the component's underlying <button /> element because we're spreading ( {... props} ) that props through to it. In the test, we create a ref so that we can pass it to the rendered Button and later to the Simulate. click call.

How do you test a functional component in a React?

Test With Shallow, Mount, or Render There are three ways to load a React component with Enzyme: shallow(<Component />) : It tests components in isolation from the child components they render. mount(<Component />) : It tests components as well as their children. It enables testing the full lifecycle of components.


2 Answers

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.

like image 67
jonowzz Avatar answered Oct 19 '22 23:10

jonowzz


I found that this syntax works better for me:

  const emailInput = component.refs.userEmailInput;
  emailInput.value = '[email protected]';
  Simulate.change(component.refs.userEmailInput);

The second line updates the input with the text, '[email protected]'. The last line triggers the change.

like image 1
Matt Goo Avatar answered Oct 19 '22 22:10

Matt Goo