Reputation: 75
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
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:
I'd love there to be a better one and hopefully someone will suggest something in the comments.
Upvotes: 10
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