A Tiny Pro Tip For Speeding Up Jest Tests

tldr; If you want to run specific Jest tests and skip the rest don't use -t. It'll scan every other test in the suite and take wayyy longer.


So, recently I switched from using Mocha for all my JavaScript unit testing to Jest. Like with most new things I found myself googling a lot... no exception when I wanted to learn the syntax for running a specific test or suite of tests without muddying things up with .only.

The first thing I came across (and probably the first thing you will find) is this post from Stack Overflow: https://stackoverflow.com/questions/42827054/how-do-i-run-a-single-test-using-jest

OK, looks like the secret is the -t flag. So if you have a describe called some tests you would run just that describe like so...

jest -t "some tests"

Now if you're coming from the world of Mocha you might be frustrated to find that this scans the entire suite and runs only the specified tests as it comes across them. If your test suite is sufficiently large, however, even just scanning the tests and not running them can take a long time. It acts the same even with .only.

For a few weeks, I just assumed this is how life had to be until I got fed up with it.

I don't remember where I found it (it wasn't easy) but basically if you drop the -t it'll predetermine which tests to run and run only those. Huge difference.

For a comparison within my own test suite, here's with -t:

And without -t:

That is a crazy difference.

An interesting side note jest --watch will only run suites where a test has changed so if you're using that exclusively you don't have to worry about this nonsense.

One last pro tip, if you're running Jest tests via NPM it's going to look something like:

npm run jest -- "my suite"

I'd suggest aliasing `npm run jest --` in your bash profile.