问题描述
我正在使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0测试React组件.
I'm testing a React component using Jest v16.0.1, react-test-renderer v15.4.0 and react-addons-test-utils v15.4.0.
该组件已呈现一个按钮:
The component has rendered a button:
<button
type="button"
className="btn btn-lg btn-primary btn-danger"
disabled={this.state.cancelButtonDisabled}
onClick={() => this.handleCancel()}
ref="cancelButton"
>Cancel</button>);
在我的测试中,我像这样渲染组件:
And in my test I'm rendering the component like so:
const component = renderer.create(
<MyComponent />
);
const instance = component.getInstance();
// This works but is ugly
component.toJSON().children[1].children[0].props.onClick();
// This doesn't work
ReactTestUtils.Simulate.click(instance.refs.cancelButton);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
模拟单击此按钮的推荐方法是什么?您可以遍历组件的JSON表示形式,但似乎应该是一种更好的方法.
What is the recommended way to simulate a click on this button? You can traverse the JSON representation of the component but it seems like their should be a better way.
在我使用ReactTestUtils.renderIntoDocument之前,您可以使用对ReactTestUtils.Simulate.click
Before when I was using ReactTestUtils.renderIntoDocument you could pass in a reference to the component using refs to ReactTestUtils.Simulate.click
我已经看到了这个问题-如何与由ReactTestRenderer/Jest 渲染的组件,但我认为API已更改,因为我的组件实例没有find()方法.
I've seen this question - How to interact with components rendered by ReactTestRenderer / Jest but I assume the API has changed as my component instance has no find() method.
推荐答案
我找到了解决方案.由于您使用的是React,因此我假设onClick处理程序函数作为prop的一部分传递给按钮.因此,您可以通过按钮的道具来访问它.
I have found a solution. Since you are using react, I assume that the onClick handler function is passed to the button as a part of the props. So you can access it through button's props.
component.root.findByType('button').props.onClick();
或者,如果您有多个按钮,则可以执行以下操作:
Or if you have more than one button, you can do this:
component.root.findByProps({ className: "btn btn-lg btn-primary btn-danger" }).props.onClick();
这篇关于React Test Renderer模拟元素点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!