In this article, I will show you some tips on how to use Jest efficiently when working on large applications. When working on a site with thousands of tests, often you need some tricks up your sleeve to work efficiently. This is a simple no nonsense guide that will help you in these situations. First, if your project has thousands of unit tests, running all the unit tests locally every time you want to make a change is not a good investment of time. Instead of running a script like this:
A more optimal strategy is to limit the tests being run to the component you are currently working on. This will save you time which will prevent you from having to wait for unrelated tests to run. Limiting which tests will be run can be done by specifying the file you want Jest to run against, like this:
This approach is much more efficient, especially if you have only touched a very small area in the codebase. The next tip can come in handy when you are working on a very brittle codebase. If you have ever encountered an issue where a test fails locally, however, it builds on the server this tip can help you. When I've encountered these issues, the failing test is usually in an area you know that you haven't touched. Your hunch that the failing test is likely down to a bad reference or a stale package somewhere, however, finding the issue may take several hours. In a perfect world, you would make sure every test works before committing, however, sometimes you just need to get shit done. In these situations, you can use one of two flags. Either --testNamePattern
or -t
. Both flags allow you to limit what tests are updated. This can be done like so:
This command will only run tests whose name matches the pattern. In this example, any tests that contain my-new-test
within the name will run. In this example, this test would get triggered:
The other way to ensure that only a single test is run within a file is to use the only()
function. When you write your tests you can also include the only()
modifier after the describe
call like this:
These tips have personally helped me to save hours of my life waiting for tests to run. I hope they do the same for you, happy coding 🤘