DEV Community

Shreya Dahal
Shreya Dahal

Posted on

3

How do /you/ write tests for React components?

I have tried many strategies to go about this. I did snapshot tests for most of the simpler components; but when there is redux and other libraries involved, doing a snapshot test for even a small component turns out to be too much work; unless you shallow render. Then, the only thing you accomplish from the test is whether or not the components render.

The best way to write unit tests is to write the tests first, that way you are only considering what output you need for different conditions and not worried about the implementation. In case of testing functionality of a component, I see tests that simulate button clicks and what not. Do you write the tests after the component is complete? Doesn't it make it harder to write tests for all the cases (your tests tend to get biased by the implementation)? Or do you write them as you are writing the component?

What is your approach to writing tests for the UI? I feel like I am missing something important.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (3)

Collapse
 
vikkio88 profile image
Vincenzo •

I do TDD my actions-reducers-helpers and only snapshot tests the ui.

I find quite silly TDD components, as in:

IT SHOULD HAVE A BUTTON
  RUN
    FAILS
  add a button
  RUN
    SUCCESS

I think it slows down and does not add much.

What I usually tend to do is to leave View quite logic free, and move everything more logic related to helpers functions that I tdd.

Collapse
 
squgeim profile image
Shreya Dahal •

That's what I've been doing. I've seen some posts from avid TDD practitioners and wanted to know how they go about it beyond a simple tutorial.

Collapse
 
vikkio88 profile image
Vincenzo •

if you say something like I did on reddit, people will downvote you to death :D

here you can say it out loud, is freeing:

TDD ON COMPONENTS IS USELESS

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series