How do I simulate a click on a div element? Or a mouse move? Or text input?
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?
Simulate a Click Event In the test, we create a ref so that we can pass it to the rendered Button and later to the Simulate. click call. The onClick prop gets the value of a handleClick event handler function. That function calls done() , which is the callback to the it function`.
To test this component you'll use the type method userEvent. type() , where you'll pass in the input element as the first argument and the value as the second argument: Use userEvent.
I have found it generally better to decouple the event handlers from the state change logic, which is the stuff I actually want to test.
For example, I have a component that needs to do something in reaction to the "tab" keypress
// this is hooked up in my render function
onKeyPress: function (e) {
if (e === 9) {
e.preventDefault()
this.onTab(e.shiftKey)
return
}
..
},
onTab: function (shift) {
var newstate = states.tab(shift, this.state)
if (newstate) this.setState(newstate)
}
Then in the states.js
file I have the logic handling how I should change the state based on the current state and the fact that the user pressed the tab key. This states.tab
method is 100% unittestable because it is "pure" — no side-effects. It takes in a state, and returns the new state.
And maybe this didn't "answer the question" directly, but I'm trying to be helpful =) decoupling your state-changing logic from the event handlers will make your code a lot more testable and maintainable.
That's not to say that you never need to simulate events — it can be useful for many cases, including in a smoketest to make sure everything's wired up correctly. But I have just found that most of the time when I wanted to simulate browser events it was because my code was too coupled.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With