DEV Community

Cover image for Effortless Project Discovery: Automating Jest Multi-Project Runs in Monorepos
Sibelius Seraphini for Woovi

Posted on

Effortless Project Discovery: Automating Jest Multi-Project Runs in Monorepos

At Woovi we have more than 6k automated tests.
We have 2 monorepos: one for the backend and another for frontend, just for historical reasons. We are going to merge them in the future.

Each package in a monorepo can have different test infrastructure requirements.
To make this possible we use Jest Multi-Project-Runner feature, which enables each package to define its own test configuration.
We can have a package that needs to use Node runtime, another that needs to run using jsdom, some packages that use elasticsearch.

Automating the discovery of projects in a monorepo

Before automating the discovery of projects for Jest, we had something like this:

module.exports = {
  projects: [
   '<rootDir>/packages/a/jest.config.js',
    '<rootDir>/packages/b/jest.config.js',
    '<rootDir>/packages/c/jest.config.js',
     ...
    '<rootDir>/packages/z/jest.config.js',
   ],
}
Enter fullscreen mode Exit fullscreen mode

Our codebase and package number are growing fast.
To make sure we are testing every package, we decided to automate the project discovered based on our monorepo pattern

const getWorkspaces = require('get-yarn-workspaces');

const cwd = process.cwd();
const pkg = require('./package.json');

const cleanWorkspaces = (workspace) => {
  const workspaces = pkg.workspaces || [];

  return workspaces.reduce((acc, w) => {
    const packagesPath = `${cwd}/${w.replace(/\/\*/g, '')}/`;

    return acc.replace(packagesPath, '');
  }, workspace);
};

const getProjects = () => {
  const workspaces = getWorkspaces();

  const pkgNames = workspaces.map((pkg) => cleanWorkspaces(pkg));

  return pkgNames.reduce(
    (acc, pkgName) => [...acc, `<rootDir>/packages/${pkgName}/jest.config.js`],
    [],
  );
};

module.exports = {
  projects: [...getProjects()],
}
Enter fullscreen mode Exit fullscreen mode

The code above will find all packages in our monorepo, and automatically add them to our jest multi-project-runner configuration.
When a new package is added to our monorepo, we ensure they are part of our test suite.

To Sum Up

When you have fewer packages or a small monorepo, this kind of automation or optimization does not make sense.
However, as you scale you need to add these to reduce the entropy to work in your codebase.

This simple optimization catch a few packages that had no tests at all, and we also make the template to create a new package to always contain a basic test setup.


Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Yuyang Liu on Unsplash

Top comments (0)