For AI agents: the complete documentation index is available at https://rstest.rs/llms.txt, the full documentation bundle is available at https://rstest.rs/llms-full.txt, and this page is available as Markdown at https://rstest.rs/guide/basic/cli.md.
close
  • English
  • CLI

    Rstest comes with a lightweight CLI that includes commands such as rstest watch and rstest run.

    rstest -h

    rstest -h displays all available CLI commands and options:

    npx rstest -h
    Usage:
      $ rstest [...filters]
    
    Commands:
      [...filters]              run tests
      run [...filters]          run tests without watch mode
      watch [...filters]        run tests in watch mode
      list [...filters]         lists all test files that Rstest will run
      merge-reports [path]      Merge blob reports from multiple shards into a unified report
      init [project]            Initialize rstest configuration
    
    Options:
      -h, --help                Display this message
      -v, --version             Display version number

    Use npx rstest <command> -h to see command-specific options. For example, npx rstest init -h only shows initialization options, while npx rstest merge-reports -h only shows merge-related options.

    rstest [...filters]

    Running rstest without a subcommand runs tests in the current directory:

    $ npx rstest
    
    ✓ test/index.test.ts (2 tests) 1ms
    
      Test Files 1 passed (1)
           Tests 2 passed (2)
        Duration 189 ms (build 22 ms, tests 167 ms)

    See Filtering tests for positional filters, exact path matching, and test-name filtering.

    Watch mode

    To rerun tests automatically when files change, pass --watch or run rstest watch:

    $ npx rstest --watch

    rstest run

    rstest run performs a single test run without watching for file changes, suitable for CI environments and one-off checks.

    Use --related to treat positional arguments as source files and run only the tests that depend on those files:

    npx rstest run --related src/button.ts

    Rstest resolves related tests from the build module graph, so the same filter works for Node mode and Browser Mode projects. You can also use the Jest-compatible alias:

    npx rstest run --findRelatedTests src/button.ts

    Compilation errors in files unrelated to the requested source do not fail --related or --changed. If a test file itself fails to compile, Rstest cannot analyze its dependencies, so it may be missed by the selection and a warning is printed. passWithNoTests only permits an empty selection.

    To inspect the affected test files without running them, combine --related with rstest list:

    npx rstest list --related src/button.ts --filesOnly

    --related and --findRelatedTests are not supported in watch mode, which already reruns tests affected by file changes.

    Run changed tests

    Use --changed to collect changed files from the current Git repository and run the tests related to those files. By default, it includes unstaged, staged, and untracked files:

    npx rstest run --changed

    You can also pass a commit or branch. Rstest includes files changed between that ref and HEAD, plus local staged, unstaged, and untracked files:

    npx rstest run --changed=HEAD~1
    npx rstest run --changed=origin/main

    When a changed file matches forceRerunTriggers, Rstest runs the whole test suite instead of only related tests.

    When coverage is enabled and coverage.changed is not configured, --changed also limits coverage reports to changed source files. If a changed file matches forceRerunTriggers, Rstest runs the whole test suite and reports full coverage unless coverage.changed is explicitly enabled.

    Use rstest list to preview which tests would run without executing them:

    npx rstest list --changed --filesOnly

    --changed cannot be combined with positional filters or --related / --findRelatedTests, because it already provides the source-file filter from Git state. It is not supported in watch mode either.

    Test selection limitations

    --related and --changed use dependencies found during the build to select tests. They do not run your tests to discover which files are loaded. The following cases can cause tests to be missed:

    • Computed imports in Node mode. Requests such as import(`./shipping/${method}.mjs`), require(`./shipping/${method}.cjs`), or import(modulePath) are not tracked reliably. Changing the loaded file, or a file it depends on, may not select the test, even when the directory is written directly in the request.
    • Files referenced only by require.resolve(). Calling require.resolve('./provider.cjs') does not establish a tracked dependency on provider.cjs. Changes to that file may not select the test.
    • Files read or loaded outside the build. Examples include files read with fs.readFile(), modules loaded through custom Node loading hooks, and dependencies inside files excluded from parsing with noParse.
    • Deleted files. --changed currently excludes staged and committed deletions. Even when a deleted path is passed to --related, the build may no longer contain enough information to find its tests.

    Rstest does not automatically run all tests when these dependencies are missing, and a warning is not guaranteed. Use npx rstest run for a full test run in these cases. For files read or loaded outside the build, forceRerunTriggers can make --changed run the full suite when it detects a matching file change.

    Run a shard

    Use --shard <index>/<count> to split test files into several shards for parallel execution. count is the total number of shards and index (1-based) is the shard to run:

    # Split tests into 3 shards, run the 1st shard
    npx rstest run --shard 1/3

    In CI/CD, you can split the suite across jobs to reduce total run time, then merge the per-shard reports with rstest merge-reports.

    Test files are sorted by the SHA-1 hash of their path relative to the root of the Rstest run, with path separators normalized to /. This spreads files from the same directory across shards while keeping the result consistent across runs and checkout locations. Sharding happens during test-file scanning, before the build. Make sure 1 <= index <= count.

    Files are distributed evenly across shards, with any remainder assigned one file at a time to the first shards. For example, 10 files split into 3 shards produce 4, 3, and 3 files, respectively.

    rstest watch

    rstest watch runs tests in watch mode and reruns affected test files when test files or their dependencies change.

    If you set Rspack's watchOptions.ignored to a function, that function controls all watch exclusions. When dev.writeToDisk is enabled, return true for the build output directory and its contents so writing build artifacts does not trigger another compilation.

    rstest list

    rstest list prints matching tests without executing them. By default, it prints the full name of each matching test:

    $ npx rstest list
    
    a.test.ts > test a > test a-1
    a.test.ts > test a-2
    b.test.ts > test b > test b-1
    b.test.ts > test b-2

    rstest list inherits Rstest's filtering options (except -f, --onlyFailures), so you can filter files directly or use -t to match test names:

    $ npx rstest list -t='test a'
    
    a.test.ts > test a > test a-1
    a.test.ts > test a-2

    Use --filesOnly to print only the matching test file paths:

    $ npx rstest list --filesOnly
    
    a.test.ts
    b.test.ts

    Use --json to print tests as JSON or write the output to a file:

    $ npx rstest list --json
    
    $ npx rstest list --json=./output.json

    In Browser Mode, rstest list evaluates test files in each selected browser instance without running test bodies. With --filesOnly, it lists each matching file once per selected instance without launching browsers. When a project selects multiple instances, --json identifies each by its instance project name, such as web (chromium) or web (firefox).

    Use --includeSuites to include test suites alongside test cases:

    $ npx rstest list --includeSuites
    
    a.test.ts > test a
    a.test.ts > test a > test a-1
    a.test.ts > test a-2
    b.test.ts > test b
    b.test.ts > test b > test b-1
    b.test.ts > test b-2

    Use --printLocation to include file paths and line/column locations:

    $ npx rstest list --printLocation
    
    a.test.ts:4:5 > test a > test a-1
    a.test.ts:9:3 > test a-2
    b.test.ts:4:5 > test b > test b-1
    b.test.ts:9:3 > test b-2

    Use --summary to append a compact summary after the list output:

    $ npx rstest list --summary
    
    a.test.ts > test a > test a-1
    a.test.ts > test a-2
    b.test.ts > test b > test b-1
    b.test.ts > test b-2
    c.test.ts > test c it each 0
    c.test.ts > test c it for 0
    c.test.ts > test c it runIf
    c.test.ts > test c it skipIf
    
     Test Files 3 matched
          Tests 8 matched

    When used with --json, --summary changes the JSON output shape from an array to an object with items and summary fields.

    rstest merge-reports

    rstest merge-reports merges blob reports generated by multiple test shards into a unified report when running tests across CI machines with --shard.

    Workflow

    1. Run each shard with the blob reporter to generate blob report files:
    # On CI machine 1
    npx rstest run --shard 1/3 --reporters=blob
    
    # On CI machine 2
    npx rstest run --shard 2/3 --reporters=blob
    
    # On CI machine 3
    npx rstest run --shard 3/3 --reporters=blob
    1. Collect all .rstest-reports/ directories into a single location, then merge:
    npx rstest merge-reports

    By default, blob reports are read from .rstest-reports/ in the project root. You can specify a custom path:

    npx rstest merge-reports ./custom-reports-dir

    The merge command will:

    • Combine test results from all blobs
    • Run configured reporters (e.g., default, junit) with the merged data
    • Merge the coverage collected by all blob-producing runs (if coverage is enabled)
    • Apply coverage.include once to add files that none of those runs tested
    • Generate coverage reports and check thresholds against the unified result

    With coverage providers that support deferred finalization, runs using the blob reporter skip coverage report generation and threshold checks. Runs without the blob reporter finalize coverage normally, including sharded runs. Older providers retain their existing per-run finalization behavior. Enable coverage for merge-reports through your configuration or the --coverage flag so the merge job can finalize coverage. merge-reports accepts the same --coverage.* options as rstest run. Coverage options passed only to a blob-producing run are not stored in its blob, so define finalization options such as coverage.include, coverage.reporters, and coverage.reportsDirectory in the configuration file or repeat them on merge-reports.

    Use --cleanup to remove the blob report inputs after merging. The directory is also removed when it becomes empty. If coverage.reportsDirectory is the blob directory or one of its subdirectories, generated coverage reports and their containing directory are retained:

    npx rstest merge-reports --cleanup

    rstest init

    rstest init creates starter configuration for supported project types:

    npx rstest init

    Currently, browser is the available initializer:

    npx rstest init browser

    Use --yes to skip the interactive prompt and apply the default setup:

    npx rstest init browser --yes

    CLI options

    Rstest CLI options are registered per command rather than shared globally across every command.

    Test commands

    rstest, rstest run, and rstest watch share the same test runtime options, except --related, --findRelatedTests, --changed, and --shard, which are rejected in watch mode:

    FlagDescription
    --bail [number]Abort the test run after the specified number of test failures, see bail
    --browser, --browser.enabledRun tests in Browser Mode, see browser
    --browser.headlessRun browser in headless mode (default: true in CI), see browser
    --browser.instances <name>Run only the configured browser instances matching chromium, firefox, or webkit; comma-separated or repeatable (default: all configured instances), see browser
    --browser.name <name>(Deprecated) Single browser to use; use --browser.instances instead, see browser (deprecated)
    --browser.port <port>Port for the Browser Mode dev server, see browser
    --browser.providerOptions.*Provider-specific browser options, see browser.providerOptions
    --browser.screenshotFailuresSave a screenshot for each failed browser test. Use --browser.screenshotFailures.clean=false to keep screenshots across runs. See browser.
    --browser.strictPortExit if the specified port is already in use, see browser
    --changed [commit]Run tests related to changed files in the current Git repository, optionally since a commit
    --clearMocksAutomatically clear mock calls, instances, contexts and results before every test, see clearMocks
    -c, --config <config>Specify the configuration file, can be a relative or absolute path, see Specify config file
    --config-loader <loader>Specify the config loader (auto | jiti | native, default: 'auto'), see Rsbuild - Specify config loader
    --coverageEnable code coverage collection, see coverage
    --coverage.allowExternalCollect coverage for files outside the project root, see coverage.allowExternal
    --coverage.changed [commit]Collect coverage only for changed files in the current Git repository, optionally since a commit
    --coverage.cleanClean the coverage directory before running tests, see coverage.clean
    --coverage.enabledEnable code coverage collection, see coverage.enabled
    --coverage.exclude <pattern>Exclude files from coverage collection, see coverage.exclude
    --coverage.include <pattern>Include files for coverage collection, see coverage.include
    --coverage.provider <provider>Choose the coverage provider (istanbul | v8), see coverage.provider
    --coverage.reporters <reporter>Specify coverage reporter(s) (repeatable), see coverage.reporters
    --coverage.reportOnFailureGenerate coverage reports even when tests fail, see coverage.reportOnFailure
    --coverage.reportsDirectory <dir>Directory to store coverage reports, see coverage.reportsDirectory
    --detectAsyncLeaksDetect async resources that leak after tests finish, see detectAsyncLeaks
    --dev.writeToDiskWrite test temporary files to disk, see dev.writeToDisk
    --disableConsoleInterceptDisable console intercept, see disableConsoleIntercept
    --exclude <exclude>Exclude files from test, see exclude
    --federationEnable Module Federation compatibility mode, see federation
    --findRelatedTestsAlias for --related for Jest compatibility
    --globalsProvide global APIs, see globals
    -h, --helpDisplay help for command
    --hideSkippedTestFilesDo not display skipped test file logs, see hideSkippedTestFiles
    --hideSkippedTestsDo not display skipped test logs, see hideSkippedTests
    --hookTimeout <value>Timeout of hook in milliseconds, see hookTimeout
    --include <include>Specify test file matching pattern, see include
    --includeTaskLocationCollect test and suite locations, see includeTaskLocation
    --isolateRun tests in an isolated environment, see isolate
    --logHeapUsagePrint heap usage for each test, see logHeapUsage
    --maxConcurrency <value>Maximum number of concurrent tests, see maxConcurrency
    -f, --onlyFailuresRun only the test files that failed in the previous run, see onlyFailures
    --output.cleanDistPathClean test temporary files before the test starts, see output.cleanDistPath
    --output.emitAssetsEmit imported static assets, see output.emitAssets
    --output.moduleOutput JavaScript files in ES module format, see output.module
    --passWithNoTestsAllows the test suite to pass when no files are found, see passWithNoTests
    --pool <type>Shorthand for --pool.type, see pool
    --pool.execArgv <arg>Additional Node.js execArgv for worker processes (repeatable), see pool
    --pool.maxWorkers <value>Maximum number or percentage of workers, see pool
    --pool.memoryLimit <limit>Memory recycling threshold for forks with isolate: false (RSS) and VM pools (V8 heap), see pool
    --pool.type <type>Specify the test pool type, see pool
    --printConsoleTracePrint console traces when calling any console method, see printConsoleTrace
    --project <name>Only run tests for the specified project, see Filter by project name
    --relatedTreat positional arguments as source file paths and only run related tests
    --repeats <repeats>Number of additional runs for each individual test, see repeats
    --reporters, --reporter <name>Specify the test reporter(s), see reporters
    --resetMocksAutomatically reset mock state before every test, see resetMocks
    --restoreMocksRestore spied object methods before every test, see restoreMocks
    --retry <retry>Number of times to retry a test if it fails, see retry
    -r, --root <root>Specify the project root directory, see root
    --shard <index/count>Split tests into several shards, see sharding
    --silent [value]Silence intercepted test console output, or keep logs only for failed tasks with passed-only, see silent
    --slowTestThreshold <value>The number of milliseconds after which a test or suite is considered slow, see slowTestThreshold
    --source.tsconfigPath <path>Path to the tsconfig.json file, see source.tsconfigPath
    --teardownTimeout <value>Milliseconds to wait for process exit after rstest run finishes; 0 exits immediately, Infinity never forces exit (default: 10000), see teardownTimeout
    --testEnvironment <name>The environment that will be used for testing, see testEnvironment
    -t, --testNamePattern <value>Run only tests with a name that matches the regex, see testNamePattern
    --testTimeout <value>Timeout of a test in milliseconds, see testTimeout
    --traceDump a Perfetto-compatible performance trace JSON file, plus a ranked markdown timing summary printed to the terminal and written next to it, see Using --trace
    --unstubEnvsRestores all process.env values that were changed with rs.stubEnv before every test, see unstubEnvs
    --unstubGlobalsRestores all global variables that were changed with rs.stubGlobal before every test, see unstubGlobals
    -u, --updateUpdate snapshot files, see update

    rstest also supports -w, --watch, which switches the default command into watch mode.

    rstest list

    rstest list supports the same options as the test commands above except -f, --onlyFailures, and adds:

    FlagDescription
    --filesOnlyOnly print matching test files
    --includeSuitesInclude suites in the output
    --json [boolean/path]Print tests as JSON or write JSON to a file
    --printLocationPrint test and suite locations
    --summaryPrint a compact summary after the list

    rstest merge-reports

    rstest merge-reports shares -h/--help, -c/--config, --config-loader, -r/--root, --reporters, --coverage, and --coverage.* flags with Test commands, and adds:

    FlagDescription
    --cleanupRemove blob report inputs after merging

    rstest init

    rstest init only accepts initialization-specific options:

    FlagDescription
    -h, --helpDisplay help for command
    --yesUse default options and skip interactive UI

    Boolean option negation

    For boolean options, prefix --no- to set them to false:

    # These are equivalent:
    npx rstest --isolate false
    npx rstest --no-isolate
    
    # More examples:
    npx rstest --no-coverage      # Disable coverage
    npx rstest --no-globals       # Disable global APIs
    npx rstest --no-clearMocks    # Disable auto-clearing mocks

    CLI shortcuts

    In watch mode on an interactive TTY, press h to print the available keyboard shortcuts:

      Shortcuts:
      f  rerun failed tests
      a  rerun all tests
      u  update snapshot
      t  filter by a test name regex pattern
      p  filter by a filename regex pattern
      c  clear screen
      q  quit process

    Press h at any time to display this shortcut list.

    Note

    CLI shortcuts are only available when running Rstest in watch mode (rstest watch or rstest --watch) and when stdin is an interactive TTY.