Front-end (React) Snapshot Testing with Jest: What is it for?

Datetime:2017-04-12 06:20:21         Topic: Test Engineer  React  Front-end Development          Share        Original >>
Here to See The Original Article!!!

First of all, it is important to highlight that each type of testing differs and have specific purposes. Unit Testing for example validates that each unit of the software performs as expected. Integration Testing ensures that the units work good together. User Interface Testing (End-to-end Testing) tests the application interfaces by the user perspective.

There are also some techniques like Test Driven Development (TDD) which define "when you should test" (or write tests before coding) and Behavior Driven Development (BDD) that approaches "why you are coding" (or behavior and specs before coding).

Regression Testing

Snapshot Testinghas nothing to do with the previous types and techniques of testing. The snapshots are useful to ensure that the state of something will not change in future. So, it is impossible to TDD or BDD with Snapshot Testing because you should write the code first and test after.

Snapshot Testing is a type of Regression Testing which is intended to verify that a previously developed and tested Software performs correctly after change.

Testing declarative interfaces and integration

The following Cart Item component example is frequently covered by tests. Let's think about it. But first, make sure you realize that the code is declarative, without any kind of logic.

It is difficult to mind and justify testing of declarative code. As pointed in these article , the task of testing declarative code ends up with a test that tells what the declaration itself does. But with less readability and intent. Indeed, declarative code is in fact formal specification .

It is fair that a BDD test case ensures that the quantity and image appears on the interface. These two assets are part of the feature specification: Cart Items should have image and quantity.

Also, it's pointless to cover these with Snapshot Testing. When changing it in the future you intentionally do so. But on the other hand, the Cart (or other components) could snapshot its integration with the Cart Item . Maybe the developer who changed Cart Item doesn't know that Cart uses it.

Legacy and poor tested code

In my humble opinion, a project with a legacy code base that should be evolved is the best fit for Snapshot Testing. With this type of test it's easy to create a minimum test code coverage without wasting time with Unit Testing.

Take a look at an example of a Snapshot Test on an application that uses React and Enzyme . Note that I used render Enzyme method instead of shallow or mount because I intent to test the final HTML result.

If you are on a project like this, I wish you the best of luck and also advise you to look at tools like PhantomCSS that automates Visual Regression Testing .


Put your ads here, just $200 per month.