在为React js编写测试时如何模拟浏览器事件? [英] How do I simulate browser events when writing tests for React js?
问题描述
如何模拟div元素的点击?还是鼠标移动?或文本输入?
How do I simulate a click on a div element? Or a mouse move? Or text input?
如何在服务器端nodejs环境中执行此操作,如mocha?
如何在浏览器环境中使用像karma这样的跑步者?
How do I do it in a server side nodejs environment, like mocha? And how do I do it in a browser environment, with a runner like karma?
推荐答案
自版本React 0.9起,我们已经包含 ReactTestUtils ,这是一小组工具来帮助我们你测试你的组件。最有用的部分是事件模拟 - 您可以运行 ReactTestUtils.Simulate.click(node)
,以便使用React的合成事件系统模拟点击事件。
Since version React 0.9, we've included ReactTestUtils which is a small bundle of tools to help you test your components. The most useful part of it is event simulation -- you can run ReactTestUtils.Simulate.click(node)
in order to simulate a click event using React's synthetic event system.
还有一些其他有用的实用程序用于对DOM结构进行断言。只需下载开发插件版本( react-with-addons.js
)并将其拉出来:
There's also a few other useful utilities there for making assertions about the DOM structure. Just download the development addons build (react-with-addons.js
) and pull it out like so:
var ReactTestUtils = React.addons.TestUtils;
ReactTestUtils.Simulate.click(node);
如果此处有任何不清楚的地方,请告诉我。
Let me know if anything's unclear here.
这篇关于在为React js编写测试时如何模拟浏览器事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!