简体   繁体   English

在React with Jest中测试模拟表单输入

[英]Test simulating form input in React with Jest

I'm testing out the form input of a React component with Jest but I'm having trouble finding the best way to select the form's input field for entry using React TestUtils. 我正在使用Jest测试React组件的表单输入,但是我很难找到使用React TestUtils选择表单输入字段的最佳方法。 The documentation online shows an example using refs , but the React docs also state that refs should only be used on the parent and not the children of the component. 在线文档显示了使用refs的示例,但React文档还声明refs应仅用于父组件而不是组件的子组件。 Should I be attaching refs to each input field or is there a better way to traverse the DOM and select the particular element so I can simulate a click event on it? 我应该将refs附加到每个输入字段,还是有更好的方法来遍历DOM并选择特定元素,以便我可以在其上模拟点击事件?

This is my render 这是我的渲染

render (
    <form className="products">
      <input onChange={this.handleName} name="name" type="text" />
      <input onChange={this.hanndleAge} name="age" type="text" />
    </form>
)

and my test 和我的考验

it('Should parse input fields', () => {
   Product = TestUtils.renderIntoDocument(<ProductComponent />);

   // This returns all the inputs but how do tell them apart? 
   let inputs = TestUtils.scryRenderedDOMComponentsWithTag(Product, 'input');
});

You shouldn't save refs if the only reason you want to use them is to be able to test your component. 如果您想要使用它们的唯一原因是您能够测试组件,则不应保存ref。

inputs variable is a regular array with all the results, you can get to the desired result by index. inputs变量是包含所有结果的常规数组,您可以通过索引获得所需的结果。

it('Should parse input fields', () => {
   Product = TestUtils.renderIntoDocument(<ProductComponent />);

   // This returns all the inputs but how do tell them apart? 
   let inputs = TestUtils.scryRenderedDOMComponentsWithTag(Product, 'input');

   let firstInput = inputs[0];
   let secondInput = inputs[1];
});

You can also use regular browser API to traverse the DOM tree after you isolate the component's primary DOM element (in your case it's form ): 在隔离组件的主DOM元素(在您的情况下是它的form )之后,您还可以使用常规浏览器API遍历DOM树:

it('Should parse input fields', () => {
   Product = TestUtils.renderIntoDocument(<ProductComponent />);

   let node = ReactDOM.findDOMNode(Product);

   let firstInput = node.querySelector("[name=name]");
   let secondInput = node.querySelector("[name=age]");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM