Search code examples
reactjsreact-nativejestjstdd

How can i use Jest to test a function inside a stateless component?


I need to test a function inside my stateless component as the source code below:

function App(props) {
  const handleItemClick = () => {
    if (true) {
      props.doanything();
    }
  }

  return (
    <div onClick={handleItemClick}>
      App
    </div>
  );
}

Solution

  • You should not test inner (private) items, it is considered bad practice to test internal implementation, instead, try to mimc user interaction with your component. In your case simulate a click on the div.

    If you are using Enzyme, you can grab the div via wrapper.find and then div.simulate('click').

    I have a common sentence that I use a lot, "If it is hard to test you probably trying to test something wrong".