Published on

How to Speed up Jest Test Runs by Splitting and Parallelising Them

  • Name

If you write functional tests using Jest and React testing library for your web apps and prefer writing them over unit tests, then soon you will realise that as your app grows, the number of tests will grow.

And soon you will land up in a situation that your tests runs is taking minutes or hours (if you app is huge) which increases your build time.


Jest version ≥ 28

If you are using Jest version 28+, then you can easily use the test sharding feature through which you can split your tests into as many blocks as you want and then run them in parallel using parallel jobs in your CI setup.

I read a very good blog post about how to use the jest shards feature and integrate with you CI setup. You can find it here.

Jest version < 28

However, this blog post is for those who cannot migrate to Jest 28 due to the breaking changes they have introduced, and are stuck on older versions.

There is still a way to create your own shard and run both of them in parallel.

Suppose your web app is structured in the below way:

 - features  
 - FeatureA  
 - components/  
 - tests/  
 - helpers/  
 - FeatureB  
 - comonents/  
 - tests/  
 - helpers/  
 - FeatureC  
 - comonents/  
 - tests/  
 - helpers/

The main objective here is to identify how you can virtually divide your tests runs into meaningful shards. In the above simple example, we can easily split the whole test runs into two (or even three) by running them for FeatureA separately and FeatureB and FeatureC separately

So we will have two CI jobs runnig in parallel:

CI job 1 — Runs tests for FeatureA

CI job 2 — Runs tests for all features except FeatureA

How to achieve it

For this, you will need to tweak some jest config parameters as shown below:

So here we are just making use of two jest config properties which are testMatch and testPathIgnorePatterns to achieve what we want.

Now let’s see what we need to change in package.json.

So we have created two scripts test-shard-one and test-shard-two which you can call whenever you invoke your test scripts in the CI config.

CI job 1 — yarn test-shard-one

CI job 2 — yarn test-shard-two


I hope this simple tweak will help you speed up your Jest test runs.