reactjs – React Test Renderer模拟元素上的点击
发布时间:2020-12-15 20:40:48 所属栏目:百科 来源:网络整理
导读:我正在使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0测试React组件. 该组件已呈现一个按钮: button type="button" className="btn btn-lg btn-primary btn-danger" disabled={this.state.cancelButtonDisabled} onClick=
我正在使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0测试React组件.
该组件已呈现一个按钮: <button type="button" className="btn btn-lg btn-primary btn-danger" disabled={this.state.cancelButtonDisabled} onClick={() => this.handleCancel()} ref="cancelButton" >Cancel</button>); 在我的测试中,我正在渲染组件: 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表示,但看起来它们应该是更好的方法. 在我使用ReactTestUtils.renderIntoDocument之前,您可以使用refs将组件的引用传递给ReactTestUtils.Simulate.click 我已经看到了这个问题 – How to interact with components rendered by ReactTestRenderer / Jest但我认为API已经改变,因为我的组件实例没有find()方法.
我找到了解决方案.由于您正在使用react,我假设onClick处理函数作为props的一部分传递给按钮.所以你可以通过按钮的道具来访问它.
component.root.findByType('button').props.onClick(); 或者,如果您有多个按钮,则可以执行以下操作: component.root.findByProps({className="btn btn-lg btn-primary btn-danger"}).props.onClick(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |