14

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?

2 Answers 2

20

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.

12

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.

1
  • The issue you referenced has now been resolved - the way to access ReactTestUtils is to use react-with-addons.js and call React.addons.TestUtils
    – dbau
    Apr 30, 2014 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.