How to run a single test in Jest: A developer’s guide to efficient testing
Testing is an essential aspect of software development, but it can easily become time-consuming — and frustrating — to run the whole test suite e.g., in Test Driven Development. This article guides you through various methods to run a single test or specific sets of tests, with direct references to Jest’s official CLI documentation.
Default test suite
By default, running the jest
command without any arguments will execute all tests:
jest
Read more about this in the official documentation.
By pattern or filename
You can run specific tests by their filename or a pattern, making it easier to focus on a specific feature or set of tests:
jest my-test
# or
jest path/to/my-test.js
Read more about this in the official documentation.
Related to uncommitted files
Execute tests related to uncommitted files with the -o
flag, which bases the test selection on your hg/git history.
jest -o
Learn more about this feature.
Related to specific files
Use the --findRelatedTests
flag to run tests related to specific (source) files:
jest --findRelatedTests path/to/fileA.js path/to/fileB.js
Further details can be found here.
By spec name
Run a test by its spec name using the -t
flag. This matches against the name in the describe
or test
blocks.
jest -t name-of-spec
Get more information on this from the official docs.
Watch mode for targeted testing
Jest’s watch mode lets you run tests as you change your code. By default, jest --watch
runs only tests related to changed files.
jest --watch
# or to run all tests
jest --watchAll
Discover more about Jest’s watch mode.
Conclusion
Jest offers multiple options for running a single test or a specific set of tests, making your development process more efficient. By understanding these options, you can reduce test time and concentrate on what matters most at any given time. Always refer to the official Jest CLI documentation for a comprehensive guide.
Happy Testing!