DEV Community

Discussion on: React Beginner Question Thread ⚛

Collapse
 
samithaf profile image
Samitha Fernando

Could be a silly question since I have not used React much. Recently i saw a code base using react and could not find much of unit testing. But there are lot of "snapshot" testing with Jest. I think that Jest internally compare a previously generated text output with current and break the test if it is different. But i don't think "snapshot" tests can totally replace unit testing since "snapshot" tests can't really test interactions isn't it?

Also how "snapshot" tests fit in to TDD?

Thanks.

Collapse
 
dan_abramov profile image
Dan Abramov

Snapshot tests aren’t meant to replace unit testing. They’re complementary. I suggest using snapshot tests for cases where otherwise you wouldn’t have written any tests at all.

People have different opinions about how much unit testing is useful for components. When I was building products with React I didn’t write unit tests for components at all because they were changing too often, and adjusting tests all the time would slow me down. And if some logic is complex enough to be worth testing I would extract it out of the component anyway. I also definitely didn’t use TDD for components (my personal opinion is that TDD isn’t very useful for UI code in general).

But this is tradeoff is different for every team. Some teams find more value in unit testing components. You definitely can do this with React—either with react-test-renderer or enzyme. It is up to you to decide how to balance unit tests with integration and snapshot tests in your app.

Collapse
 
samithaf profile image
Samitha Fernando

Thanks for the rapid response in the Christmas day! Another question regarding HOC. How HOC is different from decorator design pattern?

Thread Thread
 
dan_abramov profile image
Dan Abramov

I guess it’s a React-specific variation on it?

Thread Thread
 
samithaf profile image
Samitha Fernando

Probably :) but I can't really confirm since I have not used HOC in depth.

Collapse
 
duncanhaywood profile image
Duncan Haywood

Hi Dan,
Thank you for sharing your insights here. You are helping me very much in my own practices of implementing tests.
Much thanks,
Duncan Haywood.

Collapse
 
daniel15 profile image
Daniel Lo Nigro

But i don't think "snapshot" tests can totally replace unit testing since "snapshot" tests can't really test interactions isn't it?

A snapshot is simply a different way of performing an assertion, instead of using expect(...).toBe(...). You can write any type of test using snapshots.

Collapse
 
dan_abramov profile image
Dan Abramov

That’s a great point, you actually can test interactions with multiple snapshots.