React 测试渲染器模拟元素上的点击 [英] React Test Renderer Simulating Clicks on Elements
问题描述
我正在使用 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.
组件渲染了一个按钮:
<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 处理函数作为 props 的一部分传递给按钮.所以你可以通过按钮的 props 访问它.
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 测试渲染器模拟元素上的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!