daviddguedes
daviddguedes

Reputation: 75

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>
  );
}

Upvotes: 5

Views: 10392

Answers (2)

Wide Awake
Wide Awake

Reputation: 1469

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.

Upvotes: 10

felixmosh
felixmosh

Reputation: 35473

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".

Upvotes: 8

Related Questions