Member-only story

Improving testability of your react components

Kristijan
6 min readFeb 11, 2021

--

If you ask any developer about tests, they answer that tests are essential. They indicate that the code works as intended and that your new change didn’t break something else. However, if you go into almost any React project, you can notice that their tests are not great. Many of them have a vast amount of snapshot tests and maybe some end-to-end tests. There are no proper unit tests and no event testing. So why is that? My opinion is on the way components are built. They are too large and have too much logic inside. And in this post, I am explaining how I think you should structure components to test them.

Why aren’t your components testable?

Before explaining how to structure your component, let’s cover two crucial things that make them not easily testable. And those are JavaScript scoping and not using pure functions.

JavaScript scope of the definition

When discussing the scope of definition, I am talking about areas in the code where your variable or function is visible. In JavaScript, we have a function scope. That means everything defined in a function is visible in that function but not outside of it. Today, we mostly use stateless components in React, and they are functions. Combining that with how JavaScript scope works means anything defined inside of the component is not…

--

--

No responses yet