Skip to content

Instantly share code, notes, and snippets.

@thiamsantos
Created October 25, 2021 21:09
Show Gist options
  • Save thiamsantos/a31a8965abfe326b5dcc0b6595978fe7 to your computer and use it in GitHub Desktop.
Save thiamsantos/a31a8965abfe326b5dcc0b6595978fe7 to your computer and use it in GitHub Desktop.

Partitioning CRA tests

  1. Install dependencies
$ yarn add --dev @craco/craco @jest/test-sequencer
  1. Create jest-sequencer.js and jest.config.js.

  2. Alter package.json to use the new config file.

"test": "react-scripts test",
"test": "yarn jest --config=jest.config.js",
  1. Add the envs JEST_TOTAL_PARTITIONS, JEST_PARTITION to the CI config file
  test:
    needs: install
    name: Test
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        jest-total-partitions: [4]
        jest-partition: [1, 2, 3, 4]

    steps:
      - name: Check out Git repository
        uses: actions/checkout@v2

      - name: Set up Node.js
        uses: actions/setup-node@v1
        with:
          node-version: 14.17.4

      - name: test
        run: yarn test
        env:
          JEST_TOTAL_PARTITIONS: ${{ matrix.jest-total-partitions }}
          JEST_PARTITION: ${{ matrix.jest-partition }}
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
sort(tests) {
const totalPartitionsEnv = process.env.JEST_TOTAL_PARTITIONS;
const partitionEnv = process.env.JEST_PARTITION;
if (totalPartitionsEnv && partitionEnv) {
const totalPartitions = parseInt(totalPartitionsEnv, 10);
const partition = parseInt(partitionEnv, 10);
if (Number.isNaN(totalPartitions) || totalPartitions < 1) {
throw new Error(
`Invalid total partitions. Expected a number bigger than 1. Got: ${totalPartitionsEnv}.`
);
}
if (
Number.isNaN(partition) ||
partition < 1 ||
partition > totalPartitions
) {
throw new Error(
`Invalid partition. Expected a number between 1 and ${totalPartitions}. Got: ${partitionEnv}.`
);
}
console.log(`Running partition ${partition} of ${totalPartitions}`);
return Array.from(tests)
.sort((a, b) => (a.path < b.path ? -1 : 1))
.filter((_, i) => i % totalPartitions === partition - 1);
}
return tests;
}
}
module.exports = CustomSequencer;
const { createJestConfig } = require('@craco/craco');
const cracoConfig = require('./craco.config.js');
const base = createJestConfig(cracoConfig);
const jestConfig = {
...base,
testSequencer: "./jest-sequencer.js"
};
module.exports = jestConfig;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment