DEV Community

Michał Kardyś
Michał Kardyś

Posted on

Safer (and fast) refactoring in React

(story originally appeared at kardys.dev)

How snapshot testing is great for refactoring

Simple process

  • Snapshots work for things like data structures (as regular tests).
  • Refactoring is another great use case.

Here, I'm talking about refactoring.

To refactor, you need stability.

You work on SaaS app's frontend. New features flow in. You (or your teammates) develop new pieces of code.

What comes next?

At one point you need to refactor "little piece of code". And here you feel like you go through gates of hell.

  • you edit X - component A breaks down
  • you fix it, A works now - but suddenly Y fails

The deeper you go, the more problems arise. Even, when you try to edit just "one thing".

Does it often has to be like this?

Yes, I've exarregated situation (have I?).

Yet, we need to be sure if our refactoring works as before.

Otherwise we blow up part of the system and we are not aware of that.

How to refactor code safely without too much hassle?

Snapshot testing stabilize your code

Snapshots have had its 5 minutes.

When these arised, I've seen articles about snaps everywhere. People praising simplicity were most common.

The simplicity came with its' hidden cost. At one point I've made the same mistake.

It is:

  • too many snapshat tests.
  • too many and too fragile.

Tests have indicated changes in structure. Most often the change was meaningless (for instance, autogenerated class name change).

It builds insensitivity to further warnings. A good reason to avoid these.

But, there's great use case for snapshot testing which I learned some time ago.

Refactoring.

Refactoring with snapshot tests

The process is:

  1. You make snapshot of a component you want to refactor. (don't commit these)
  2. You refactor the code
  3. If snapshot test passes after refactor, delete test.

Test is temporary. You don't have to push it anywhere.

It is just your helper, so you are certain that after refactoring, result looks exactly the same

Check it out.

It's:

  • simple
  • fast
  • easy

How do you refactor your code?

Top comments (0)