This video is available to students only

Testing a transform

Create tests for jscodeshift transforms for a faster feedback loop

When working on a transform, it likely only needs to be run once on a codebase, unless it's intended to be reused multiple times. For example, the react-codemod package is a set of transforms to help update React APIs. These transforms are intended to be run on many codebases.

The react-codemod transforms are a good example of when testing can be helpful, since they'll be run on many codebases. However, even if a transform is only intended to be run once on your codebase, writing tests can be a good way to streamline development.

The process we've been using up to this point has been to work on the transform, run it on the codebase, undo the changes (git reset), and repeat. The test helpers from jscodeshift can help turn this into a more automated test-driven development process, and make the iteration much faster by removing the need to run it on the codebase and undo the changes.

Adding unit tests#

Let's continue with the same jscodeshift transform from the previous lesson. We can start by creating new directories for the test cases and test fixtures.

The test utils require these exact directory names. They also require the tests be written with Jest, a popular JavaScript testing framework. The tests can be written in JavaScript or TypeScript. Since the transform is TypeScript, it makes sense to also write the tests in TypeScript.

This requires some extra setup, with either babel or ts-jest. There are tradeoffs with either approach, but the babel approach only transpiles and doesn't perform any type-checking. The ts-jest package is a bit easier to set up, and also performs type-checking. Either approach will work, but let's install the necessary dependencies to get ts-jest working.

Now, with the test tooling set up, it's time to add a test. Create a new transform-test.ts file in the __tests__ directory.

In this case, we'll have one test file because there's one transform.

The test fixtures will contain input and output pairings, and there can be as many as needed. The test currently expects test fixtures with the name basic suffixed with .input and .output along with the extension which will be .js in this case.

Next, add these two files in __testfixtures__: basic.input.js and basic.output.js.

Basic case#

The input will be what is passed into the transform, and the defineTest helper will assert the transform output matches the test fixture output.



We can then add a test script to package.json to make it easier to run the tests.

The test can be run with npm test, and it should pass.


This page is a preview of Practical Abstract Syntax Trees

Start a new discussion. All notification go to the author.