Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
  );
}
like image 217
daviddguedes Avatar asked Dec 03 '22 18:12

daviddguedes


1 Answers

As suggested - if you can simply test your functionality by simulating user clicks then do take that approach. BUT, saying that testing internal implementation is 'bad practice' is unhelpful and impractical.

There is still a strong case for testing a function directly. Especially when your component is complex with several nested components making asynchronous calls to servers before the function you want to test can be run.

In this scenario - you're left with two choices, that I'm aware of:

  1. Move the function out of the functional component scope, export that and test it (NB, you'll possibly need to pass in quite a few props so this can look ugly)
  2. Use a class component. This way you can reference the function directly.

I'd love there to be a better one and hopefully someone will suggest something in the comments.

like image 107
Wide Awake Avatar answered Dec 06 '22 08:12

Wide Awake