How to shard Jest tests in GitHub Actions


This article goes over how to shard Jest tests in GitHub Actions.

Workflow

Shard Jest test suite using GitHub Actions matrix:

# .github/workflows/test.yml
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        shard: [1/2, 2/2]
    steps:
      - npx jest --shard=${{ matrix.shard }}

Increase to 3 shards:

# .github/workflows/test.yml
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        shard: [1/3, 2/3, 3/3]
    steps:
      - npx jest --shard=${{ matrix.shard }}

Sharding will speed up the time it takes for tests to run since they run in parallel, but it will also increase the total duration, which will increase the billable time.

Code Climate

Upload the coverage to Code Climate:

# .github/workflows/test.yml
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        shard: [1, 2]
    steps:
      - npx jest --shard=${{ matrix.shard }}/${{ strategy.job-total }}
      - uses: remarkablemark/setup-codeclimate@v2
      - run: cc-test-reporter format-coverage -t lcov -o coverage/climate.${{ matrix.shard }}.json
      - uses: actions/upload-artifact@v4
        with:
          name: coverage-${{ matrix.shard }}
          path: coverage/climate.*.json
          retention-days: 1

  coverage:
    runs-on: ubuntu-latest
    needs: [test]
    steps:
      - uses: actions/download-artifact@v4
        with:
          path: coverage
          pattern: coverage-*
          merge-multiple: true
      - uses: remarkablemark/setup-codeclimate@v2
      - run: |
          cc-test-reporter sum-coverage coverage/*
          cc-test-reporter upload-coverage
        env:
          CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}


Please support this site and join our Discord!