How to Isolate Tests in Jest

How to Isolate Tests in Jest

test.only() and test.skip()

ยท

2 min read

A Note on the Series:

Fast Fridays ๐ŸŽ is a series where you will find fast, short and sweet tips/hacks that you may or may not be aware of. I will try to provide these (fairly) regularly on Fridays.

When writing unit tests with Jest, I often want to isolate a particular test case. I find this especially true when working within a test suite that has gotten pretty large due to the number of features associated with a particular component.

Instead of taking the manual approach and commenting out the tests cases I want to ignore for the moment, Jest provides two helper methods test.only() and test.skip() that makes isolating specific tests a lot simpler.

test.only()

The test.only() method is beneficial if you want to target ๐ŸŽฏ individual tests within a suite. By default, Jest will run all tests within a suite unless instructed otherwise. When a minimum of one test case uses this method, Jest will only run the test cases that reference the .only() method.

I find myself using test.only() quite a bit these days. A common workflow for me is to implement a feature and then pinpoint the individual tests that I want to hone in on. This allows me to reduce the amount of output in the terminal and focus on the main task at hand.

test.skip()

The test.skip() method is helpful if you want to omit โฉ certain tests from a suite. When the .skip() method is used, Jest will skip over the relevant test case when running the test suite. I don't find myself using this method as often as test.only(), but I still find it to be a beneficial method to have in my back pocket.

Screen Shot 2021-12-16 at 12.54.32 AM.png Output when test.only() or test.skip() is used on an individual test.

๐Ÿšจ Warning: Make sure to remove the .only() or .skip() methods before committing your code. These methods are only meant to be used for debugging purposes and should not be used in final tests.

El Fin ๐Ÿ‘‹๐Ÿฝ

I hope this quick tip can be useful to you the next time you have to write tests. For an exhaustive list of global objects and methods associated with the test object, take a look at the official documentation .

As always, thank you for reading, and happy coding!

Resources