Categories

Meta

testing

Snapshot testing is the latest craze. Popularized by Facebook’s Jest testing framework, snapshot testing is a simple way to add regression testing into your application.

What is regression testing, you ask? Regression testing is testing that the output did not change from what it previously returned.

Take the following example:

In this handler we are retrieving a list of users, optionally filtered by the request context. We can use ColdBox’s integration testing capabilities to test that this code is coming back correctly.

This is a great test! It will make sure that this users endpoint returns the values we expect.

Fast-forward a month or two (or maybe just a few weeks) and there is a new property on the User bean. With our current approach, our users endpoint test will fail, even though the logic hasn’t changed. We’ll need to go update our tests to match.

Not with snapshot testing. Let’s take a look at the same test using snapshot testing:

When running this test for the first time, the tests will fail mentioning that no snapshots exist.

Creating and updating snapshots is a deliberate action with snapshot testing. You have to pass a updateSnapshots url flag to create or update the snapshots for the tests ran.

Matchers that have their snapshots updated always return true. In addition, a debug message is logged with the name of the snapshot created.

The real power of snapshot tests come when you make changes. Let’s add an email field to the User bean and return it. When we run our tests now, we see the following failure:

This failure gives us the opportunity to check what changed in our system and if we were did break some existing functionality. If we did, our tests helped us catch it! If not, we can now update these snapshots by running the tests with the updateSnapshots url flag.

A really compelling use case for this is testing HTML. In fact, the snapshot intelligently normalizes HTML output so that simple indentation changes should cause the snapshot to fail.

To get started with snapshot testing in TestBox, install the testbox-snapshots module from ForgeBox. Then add the matcher in your beforeAll method and you’re good to go!

For more precise changes, make sure to include the optional java library in your load paths. It produces a diff of the files instead of just outputting the contents in their entirety. You can enable this by including the following in your tests/Application.cfc: