Test Refactoring Code I’d Like to Have

By: John Detlefs
Posted: January 13, 2022

What I want is human in the loop automated test-refactoring with the assistance of well-maintained codemods & helpful UIs. Many teams including my own have test suites that are filled with Mocha & Enzyme tests. They want to switch but the problem seems intractable because of its scope and the lack of good automation tooling. There are a bunch of different problems with these test suites that could be addressed coterminously by software trying to enter this space.

The first problem I would like to do is consolidate “it” statements, oftentimes in Enzyme tests you’ll have a test suite with 10x the number of tests the standard RTL test suite would have. I think we could have a GUI for each file that lets us choose how to consolidate it statements in each test file such that we could reduce the number of tests by something hopefully close to an order of magnitude.

The second problem is dealing with stubbed imported methods and higher order components. For the Proxyquiring / Sinon stubbing of imports, we could do better at translating existing Proxyquire / Sandbox mocks over to Jest mocks via Codemods that mostly exist. The improvements would come from identifying the myriad edge cases caused from tests written slightly different and accounting for them. For the mocking of API requests it would be interesting to consider using mock service worker instead. https://mswjs.io/ and figure out a way to identify many if not all of the api calls that the codebase makes and automatically provide at least a skeleton of their mocked behavior through with MSW.

I think another important aspect of any automated test refactoring is that the changes can be reviewed and approved incrementally. Automated test-refactoring software could spit out a summary of the changes that were made to a test file to make PRs easier to review. Not only that, but this software could help initialize the new Jest suite with reasonable defaults. The software could also keep track of how many tests you have left to write. Obviously writing this is a lot easier than writing the code to do all this, but I wanted to talk about what I would want to see made.