Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 30 ยท Getting Started

The Jest CLI and Watch Mode

Learn the Jest command line: run one file, filter tests with -t, use watch mode, collect coverage, run in band, stop early with --bail and read exit codes in CI.

Most of your time with Jest is spent running it, so it pays to know the command line. You rarely want to run the whole suite while you work on one function. You want to run one file, or one test, or have Jest re-run tests every time you save. In continuous integration you want the opposite: everything, strict, with a clear exit code.

This lesson covers the flags you will use every week. It follows describe, it and Test Organization, because several flags work on the names you give your tests.

Real versus stand-in. Jest commands are real and read-only here, since the site cannot run npm packages. The runnable stand-in implements the logic behind -t name filtering, --bail and exit codes in plain JavaScript so you can see how they decide what runs.

Running Jest

If Jest is a dev dependency, you can run it three ways. They all do the same thing:

Terminal
npm test            # runs the "test" script from package.json
npx jest            # runs the locally installed jest directly
npm test -- --bail  # note the extra -- before flags meant for jest

The -- matters: it tells npm to pass everything after it to the script. Without it, npm may swallow the flag. With npx jest, you pass flags directly.

Running one file

Anything that is not a flag is a path pattern, matched as a regular expression against full test file paths.

Terminal
npx jest src/cart.test.js     # one file
npx jest cart                 # every test file whose path contains "cart"
npx jest src/services         # every test file under that folder

Use npx jest --listTests to print which files Jest would run, without running them. It is a quick way to debug a path pattern or a testMatch setting.

Running one test by name: -t

-t (long form --testNamePattern) filters by test name, again as a regular expression. Jest matches it against the full name: the describe names and the test name joined with spaces.

Terminal
npx jest -t "total"                       # every test whose full name contains "total"
npx jest cart -t "Cart total is zero"     # combine a file filter and a name filter
npx jest -t "^Cart addItem"               # anchored: only the addItem group

Tests that do not match are reported as skipped, and the files are still loaded. This is the fastest way to focus on a single failing test without touching the code or adding .only.

Watch mode

Terminal
npx jest --watch

Watch mode keeps Jest running. Whenever you save a file, it re-runs the tests that are related to the files that changed. To work out what changed, --watch uses your version control (it expects a Git or Mercurial repository) and by default looks at files changed since the last commit. If your project is not under version control, use --watchAll, which re-runs everything on each change.

While watch mode is running, a small menu lets you steer it with single keys:

Key What it does
a Run all tests
f Run only the tests that failed last time
o Run only tests related to changed files
p Filter by file name pattern
t Filter by test name pattern
Enter Run again
q Quit

A typical loop is: start npx jest --watch, press p and type the file you are working on, then keep coding. Each save gives you feedback in under a second.

Coverage

Terminal
npx jest --coverage

Jest instruments your source files while the tests run and then prints a table of how many statements, branches, functions and lines were executed. It also writes a coverage/ folder, including an HTML report in coverage/lcov-report/index.html. Add coverage/ to .gitignore. We dig into reading and enforcing coverage in Coverage and Test Quality.

Other flags worth knowing

Flag Use
--runInBand (-i) Run all tests one after another in the current process, no workers. Easier to debug, and sometimes faster on tiny suites or slow CI machines.
--maxWorkers=2 or =50% Limit how many worker processes Jest uses.
--bail (or --bail=3) Stop after the first failing test suite (or after n failing suites).
--verbose Print every test name even when there are many files.
--ci Do not write new snapshots automatically; a missing snapshot fails instead.
--onlyChanged (-o) Run only tests related to files changed in version control.
--passWithNoTests Exit 0 when no test files are found.
--clearCache Delete Jest's transform cache, useful after strange stale behavior.
--silent Hide console.log output from your code.

To debug with a debugger, run Jest in a single process, because breakpoints and workers do not mix:

Terminal
node --inspect-brk node_modules/jest/bin/jest.js --runInBand

Then attach Chrome DevTools or your editor to the paused process.

Exit codes

Jest exits with code 0 when every test suite passed and 1 when something failed (or when no tests were found without --passWithNoTests). Continuous integration systems use that code to mark a build red or green, so you never have to read the text to know the result. In a GitHub Actions step or a git hook, npm test failing is what stops the pipeline.

The logic behind -t and --bail

This stand-in builds a list of tests with full names (describe path plus test name), applies a -t style regular expression, optionally bails after the first failure, and finishes with an exit code. Change pattern to "total", "^Cart addItem" or null, and flip bail.

JS Name filtering, bail and an exit code

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(Real --bail works per test suite, meaning per file, while this single-file stand-in stops at the first failing test.) With pattern = "Cart" the Totals test is skipped and two tests fail, so the exit code is 1. Set pattern = "formats" and the exit code becomes 0, because the only test that ran passed. That is an important point: a filtered run can be green while the full suite is red, so CI should always run everything.

A tiny watch-mode idea

Watch mode is not magic. It notices a change, decides which tests are affected, and runs them. Here is the "decide" step as a function: given a changed source file and a map of which test files import which modules, return the tests to run.

JS Which tests does a change affect?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Changing price.js re-runs two test files because both depend on it. Real Jest builds this dependency map from the files your code imports (including indirect imports), which is why watch mode stays fast even in a large project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you run only the tests whose full name contains 'total'?

    -t (--testNamePattern) filters by test name. A bare argument like 'total' is a path pattern that matches test file paths.
  2. 2. Why does npm test -- --bail need the double dash?

    npm uses -- to separate its own options from arguments for the script it runs.
  3. 3. What does --runInBand do?

    With --runInBand (-i) there are no worker processes, so a debugger can attach and logs are simpler.
  4. 4. Jest finishes a run where one test failed. What exit code does it return?

    A non-zero exit code (1) signals failure to CI systems and scripts.
  5. 5. Why should CI not rely only on a run filtered with -t?

    Filters are for local focus. CI should run the full suite so no failing test goes unnoticed.

Summary

  • Use npm test -- <flags> or npx jest <flags>; bare arguments are file path patterns.
  • -t "name" filters by full test name (describe path plus test name) with a regular expression.
  • --watch re-runs tests related to changed files (needs Git or Mercurial); --watchAll re-runs everything; keys a f o p t q steer it.
  • --coverage prints a table and writes a coverage/ folder; --runInBand helps debugging; --bail stops early; --ci stops snapshot auto-writing.
  • Exit code 0 means success and 1 means failure, which is how CI knows.

Next: Common Matchers.