Jest and the Component Driven Development (CDD)

Lautaro Gruss
Comunidad JS
Published in
2 min readJul 20, 2017
Testing React and React Native applications.

We all know about TDD right? Test-Driven Development.
The philosophy behind it is to start the development cycle by first writing a failing test and then writing the actual function, to make it pass the test it self. That is ok, but a bit sad.
I recently discovered other flow/flavor around React Components and Jest snapshot testing that makes me happier and encourages me to write more tests.

This approach makes the dev process a bit more fun than the other way around. I say, write the component first, because we need it to interact with other parts of our application as soon as possible. Then, when you´re comfortable with your component code base and you have applied all the good practices out there, write the actual test, passing the required props to the component being tested, and expect it to match the snapshot.

Snapshot testing

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.

The above statement is from the Jest documentation, and it´s 100% true.
I’ve found snapshot testing to be a quick and fun way to test Components and make sure your UI does not change unexpectedly, which is a good thing.

The test will fail if the two images do not match: either the change is unexpected, or the screenshot needs to be updated to the new version of the UI component.

That means we are not passing the expected props to our component in some parts of our application or we have adjusted the component (because we´ve refactored it). So either one or the other possibility, we need to update the test snapshot (If we´ve refactored it) executing in the terminal yarn test -u or go and fix the part in the application where we´re not using the component as we expect.

Having a test coverage between 80 and 100% makes us more confident when we need to deploy to any environment and allows applications to be more robust and easy to scale.

In closing, I really encourage React developers to use Jest for testing applications. It makes testing fun, more than ever, and more importantly, you can start applying CDD.

--

--