Simulating text entry with reactJs TestUtils

痞子三分冷 提交于 2019-12-05 12:37:22

问题


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)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24730019/simulating-text-entry-with-reactjs-testutils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!