Snapshot Testing with Ambiguity
A Technique for Ensuring Structural Integrity
While working in a single monorepo with many engineers — I’ve gained an appreciation of stability in a rapidly changing structure. Snapshot testing, recently popularized by Jest, has been widely adopted, criticized (here and here for example), and endorsed typically for React UI component testing (a good read about its effectiveness here). I find value in snapshots as one ingredient in a whole recipe of testing strategy. Testing ambiguously can have benefits. Beyond a textbook thought of software testing, snapshots can be used as a device for controlling change.
Testing Package Module Structure
In my case the need to prevent unanticipated breaking changes of packages in a Lerna based monorepo was important. The shape of modules used and maintained by a large group of collaborators needed to remain in expected form.
Consider the below exported module from “foo.js”.
And a different exported module from “zot.js”.
“index.js” exports these modules as a package.
Let’s go ahead and write a snapshot test for “index.js” as a test for our package module structure.
Behold… our snapshot…
Do I Care?
What just happened… you may be wondering. Like — why?! The reason lies in the responsibility to ensure structural integrity. Below are ways the example above could be helpful.
- In a pull request— the snapshot diff would show major package changes and lead to discussion among code reviewers.
- In adhering to specific module patterns like “tree shaking” as used by Webpack, a snapshot would illustrate module type (function vs object literal) and levels of nesting. To support tree shaking, modules should be flat.
- In making major structural changes like shifting and creating directories — a single snapshot of the package modules would ensure the shape as a whole remains as expected.
Conclusion
Every flavor of software testing has its place. Commonly a variety of tests are used together… unit tests, integration tests, etc. Snapshot testing can help provide stability in an environment of continuous change.