メインコンテンツへスキップ
Version: 30.0

Jest CLI オプション

The jest command line runner has a number of useful options. You can run jest --help to view all available options. 以下に示すオプションの多くは任意のテストを実行する際に利用できます。 Every one of Jest's Configuration options can also be specified through the CLI.

以下に簡単な概要を示します。

コマンドラインから実行する

全てのテストを実行する (既定値):

jest

パターンやファイル名で指定されたテストのみ実行する:

jest my-test # または
jest path/to/my-test.js

hg や git (の未コミットファイル) に基づいて、変更のあったファイルに関連したテストを実行する:

jest -o

Run tests related to path/to/fileA.js and path/to/fileB.js:

jest --findRelatedTests path/to/fileA.js path/to/fileB.js

Run tests that match this spec name (match against the name in describe or test, basically).

jest -t name-of-spec

ウォッチモードで実行する:

jest --watch # デフォルトで jest -o を実行
jest --watchAll # runs all tests

ウォッチモードにより特定のテストセットにフォーカスするためにファイル名やファイルパスを特定することも可能となります。

パッケージマネージャーで使用する

Jest をパッケージマネージャーで実行する時は、コマンドライン引数を Jest の引数として直接渡せます。

下のコマンドの代わりに

jest -u -t="ColorPicker"

次のように使用できます。

npm test -- -u -t="ColorPicker"

Camelcase & dashed args support

Jestは、キャメルケースとダッシュで繋いだ形式の両方をサポートしています。 次の例は同じ結果になります。

jest --collect-coverage
jest --collectCoverage

引数は次のように混ぜて使うこともできます。

jest --update-snapshot --detectOpenHandles

オプション

note

CLI options take precedence over values from the Configuration.


リファレンス

jest <regexForTestFiles>

When you run jest with an argument, that argument is treated as a regular expression to match against files in your project. パターンを与えてテストスイートを実行することができます。 パターンに一致するファイルだけが選択され、実行されます。 Depending on your terminal, you may need to quote this argument: jest "my.*(complex)?pattern". On Windows, you will need to use / as a path separator or escape \ as \\.

--bail[=<n>]

Alias: -b. Exit the test suite immediately upon n number of failing test suite. Defaults to 1.

--cache

キャッシュを使用するかを指定します。 既定値ではtrueです。 Disable the cache using --no-cache.

caution

キャッシュの無効化は、キャッシュに関連した問題が発生した場合のみ行ってください。 概して、キャッシュの無効化により Jest の実行時間は2倍になります。

If you want to inspect the cache, use --showConfig and look at the cacheDirectory value. If you need to clear the cache, use --clearCache.

--changedFilesWithAncestor

現在の変更と最後のコミットによる変更に関係するテストを実行します。 Behaves similarly to --onlyChanged.

--changedSince

指定されたブランチもしくはコミットハッシュ値以降の変更に関係するテストを実行します。 現在のブランチが指定されたブランチと大きく異なる場合、ローカルで行われた変更点のみがテストされます。 Behaves similarly to --onlyChanged.

--ci

このオプションが指定された場合、Jestは CI 環境で実行されていると仮定します。 これによって、新しいスナップショットが見つかったときの挙動が変わります。 Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with --updateSnapshot.

--clearCache

Jest のキャッシュディレクトリを削除し、テストを実行せずに終了します。 Will delete cacheDirectory if the option is passed, or Jest's default cache directory. The default cache directory can be found by calling jest --showConfig.

caution

キャッシュをクリアすると、パフォーマンスが低下します。

--clearMocks

各テストの実行前に、モックコール、インスタンス、コンテキスト、結果を自動的にクリアします。 Equivalent to calling jest.clearAllMocks() before each test. このオプションは与えられたモックの実装を削除することはしません。

--collectCoverageFrom=<glob>

A glob pattern relative to rootDir matching the files that coverage info needs to be collected from.

--colors

標準出力が端末でなくても強制的にテスト結果を強調して表示します。

note

Alternatively you can set the environment variable FORCE_COLOR=true to forcefully enable or FORCE_COLOR=false to disable colorized output. The use of FORCE_COLOR overrides all other color support checks.

--config=<path>

Alias: -c. テストの探索と実行の方法を指定する Jest の設定ファイルのパスを引数に指定します。 If no rootDir is set in the config, the directory containing the config file is assumed to be the rootDir for the project. 引数にJSON形式の値を与えることでもJestは設定として使用します。

--coverage[=<boolean>]

Alias: --collectCoverage. テストのカバレッジ情報が収集され出力に表示されるべきであることを指定します。 Optionally pass <boolean> to override option set in configuration.

--coverageDirectory=<path>

The directory where Jest should output its coverage files.

--coverageProvider=<provider>

Indicates which provider should be used to instrument code for coverage. Allowed values are babel (default) or v8.

--debug

Jestの設定に関するデバック情報を出力します。

--detectOpenHandles

開いているハンドルを収集して出力することを試みます。これにより、Jest が何も出力せずに終了するのを防ぐことができます。 Use this in cases where you need to use --forceExit in order for Jest to exit to potentially track down the reason. This implies --runInBand, making tests run serially. Implemented using async_hooks. このオプションには重大なパフォーマンスの低下があり、デバッグにのみ使用する必要があります。

--env=<environment>

すべてのテストに使用するテスト環境を指定します。 任意のファイルまたはnodeのモジュールを指定できます。 Examples: jsdom, node or path/to/my-environment.js.

--errorOnDeprecated

Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.

--expand

Alias: -e. このフラグを指定すると差分とエラーを一部ではなく全体表示します。

--filter=<file>

Path to a module exporting a filtering function. This asynchronous function receives a list of test paths which can be manipulated to exclude tests from running and must return an object with shape { filtered: Array<string> } containing the tests that should be run by Jest. Especially useful when used in conjunction with a testing infrastructure to filter known broken tests.

my-filter.js
// This filter when applied will only run tests ending in .spec.js (not the best way to do it, but it's just an example):
const filteringFunction = testPath => testPath.endsWith('.spec.js');

module.exports = testPaths => {
const allowedPaths = testPaths.filter(filteringFunction); // ["path1.spec.js", "path2.spec.js", etc]

return {
filtered: allowedPaths,
};
};

--findRelatedTests <spaceSeparatedListOfSourceFiles>

引数で渡された、スペース区切りのソースリストにあるテストを探して実行します。 コミット前に最小限必要なテストを実行するフックで使うのに便利です。 Can be used together with --coverage to include a test coverage for the source files, no duplicate --collectCoverageFrom arguments needed.

--forceExit

全テストが終了した後にJestを強制的に終了します。 テストコードにてリソースを適切にクリーンアップできない場合に便利です。

caution

This feature is an escape-hatch. Jest がテスト実行後に終了しなければ、外部リソースが占有されたままであったり、タイマー処理がコードを保留したままであるということです。 Jestが正常に終了できるよう各テスト後に外部リソースを開放することをお勧めします。 You can use --detectOpenHandles to help track it down.

--help

このページと同様に、ヘルプ情報を表示します。

--ignoreProjects <project1> ... <projectN>

Ignore the tests of the specified projects. Jest uses the attribute displayName in the configuration to identify each project. If you use this option, you should provide a displayName to all your projects.

--injectGlobals

Insert Jest's globals (expect, test, describe, beforeEach etc.) into the global environment. If you set this to false, you should import from @jest/globals, e.g.

import {expect, jest, test} from '@jest/globals';

jest.useFakeTimers();

test('some test', () => {
expect(Date.now()).toBe(0);
});
note

This option is only supported using the default jest-circus test runner.

--json

JSON形式でテスト結果を出力します。 このモードでは他の全てのテストに関する出力やユーザメッセージを標準エラー出力に出力します。

--lastCommit

最後に行ったコミットによるファイル変更に関係するテストをすべて実行します。 Behaves similarly to --onlyChanged.

--listTests

Lists all test files that Jest will run given the arguments, and exits.

--logHeapUsage

各テスト後にヒープ使用率を記録します。 メモリリークのデバッグに役立ちます。 Use together with --runInBand and --expose-gc in node.

--maxConcurrency=<num>

テストの同時実行数の最大値を設定します。 Only affects tests that use test.concurrent.

--maxWorkers=<num>|<string>

Alias: -w. テスト実行のためにworker-poolが生成するworkerの最大数を指定します。 In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases.

For environments with variable CPUs available, you can use percentage based configuration: --maxWorkers=50%

--noStackTrace

テスト結果でスタックトレースを出力しません。

--notify

Activates native OS notifications for test results. JavaScriptのテスト以外の何かに意識を集中させてしまいたくない場合に適しています。 To display the notifications Jest needs the node-notifier package, which must be installed separately.

--onlyChanged

Alias: -o. 現在のリポジトリでそのファイルに変更があったかに基づいて、どのテストを実行するのかを識別しようとします。 git/hgのリポジトリでテストを実行した場合のみ動作し、静的な依存グラフが必要です (言い換えると動的な依存グラフは必要ありません)。

--onlyFailures

Alias: -f. Run tests that failed in the previous execution.

--openHandlesTimeout=<milliseconds>

When --detectOpenHandles and --forceExit are disabled, Jest will print a warning if the process has not exited cleanly after this number of milliseconds. A value of 0 disables the warning. Defaults to 1000.

--outputFile=<filename>

Write test results to a file when the --json option is also specified. The returned JSON structure is documented in testResultsProcessor.

--passWithNoTests

ファイルが1つも存在しなくても、テストスイートがパスするようにします。

--projects <path1> ... <pathN>

Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the projects configuration option.

note

If configuration files are found in the specified paths, all projects specified within those configuration files will be run.

--randomize

Shuffle the order of the tests within a file. The shuffling is based on the seed. See --seed=<num> for more info.

Seed value is displayed when this option is set. Equivalent to setting the CLI option --showSeed.

jest --randomize --seed 1234
note

This option is only supported using the default jest-circus test runner.

--reporters

指定されたレポーターでテストを実行します。 Reporter options are not available via CLI. 複数のレポーターの例:

jest --reporters="default" --reporters="jest-junit"

--resetMocks

Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks() before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.

--restoreMocks

Automatically restore mock state and implementation before every test. Equivalent to calling jest.restoreAllMocks() before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.

--roots

Jestがファイルを検索するために使用するディレクトリのパスのリスト。

--runInBand

Alias: -i. 子プロセスのworker poolを作成せずに現在のプロセスで全てのテストを1つずつ実行します。 デバッグ時に便利です。

--runTestsByPath

パターンやファイル名で指定されたテストのみ実行します。 This avoids converting them into a regular expression and matching it against every single file.

例として、以下のファイル構成が与えられたとします。

__tests__
└── t1.test.js # テスト
└── t2.test.js # テスト

これに対して、次のパターンで実行すると、テストは実行されません。

jest --runTestsByPath __tests__/t

Output:

No tests found

However, passing an exact path will execute only the given test:

jest --runTestsByPath __tests__/t1.test.js

Output:

PASS __tests__/t1.test.js
tip

The default regex matching works fine on small runs, but becomes slow if provided with multiple patterns and/or against a lot of tests. This option replaces the regex matching logic and by that optimizes the time it takes Jest to filter specific test files.

--seed=<num>

Sets a seed value that can be retrieved in a test file via jest.getSeed(). The seed value must be between -0x80000000 and 0x7fffffff inclusive (-2147483648 (-(2 ** 31)) and 2147483647 (2 ** 31 - 1) in decimal).

jest --seed=1324
tip

If this option is not specified Jest will randomly generate the value. You can use the --showSeed flag to print the seed in the test report summary.

Jest uses the seed internally for shuffling the order in which test suites are run. If the --randomize option is used, the seed is also used for shuffling the order of tests within each describe block. When dealing with flaky tests, rerunning with the same seed might help reproduce the failure.

--selectProjects <project1> ... <projectN>

Run the tests of the specified projects. Jest uses the attribute displayName in the configuration to identify each project. If you use this option, you should provide a displayName to all your projects.

--setupFilesAfterEnv <path1> ... <pathN>

A list of paths to modules that run some code to configure or to set up the testing framework before each test. Beware that files imported by the setup scripts will not be mocked during testing.

--shard

The test suite shard to execute in a format of (?<shardIndex>\d+)/(?<shardCount>\d+).

shardIndex describes which shard to select while shardCount controls the number of shards the suite should be split into.

shardIndex and shardCount have to be 1-based, positive numbers, and shardIndex has to be lower than or equal to shardCount.

When shard is specified the configured testSequencer has to implement a shard method.

For example, to split the suite into three shards, each running one third of the tests:

jest --shard=1/3
jest --shard=2/3
jest --shard=3/3

--showConfig

Jestの設定を出力して終了します。

--showSeed

Prints the seed value in the test report summary. See --seed=<num> for the details.

Can also be set in configuration. See showSeed.

--silent

コンソール経由でメッセージを表示しないようにします。

--testEnvironmentOptions=<json string>

A JSON string with options that will be passed to the testEnvironment. The relevant options depend on the environment.

--testLocationInResults

Adds a location field to test results. レポーターでテストの場所を表示したい場合に役立ちます。

note

In the resulting object column is 0-indexed while line is not.

{
"column": 4,
"line": 5
}

--testMatch glob1 ... globN

The glob patterns Jest uses to detect test files. Please refer to the testMatch configuration for details.

--testNamePattern=<regex>

Alias: -t. 正規表現に一致する名前のテストのみ実行します。 For example, suppose you want to run only tests related to authorization which will have names like 'GET /api/posts with auth', then you can use jest -t=auth.

tip

The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks.

--testPathIgnorePatterns=<regex>|[array]

A single or array of regexp pattern strings that are tested against all tests paths before executing the test. Contrary to --testPathPatterns, it will only run those tests with a path that does not match with the provided regexp expressions.

To pass as an array use escaped parentheses and space delimited regexps such as \(/node_modules/ /tests/e2e/\). Alternatively, you can omit parentheses by combining regexps into a single regexp like /node_modules/|/tests/e2e/. These two examples are equivalent.

--testPathPatterns=<regex>

テスト実行前に全てのテストのパスに対して照合する正規表現の文字列を指定します。 On Windows, you will need to use / as a path separator or escape \ as \\.

--testRunner=<path>

カスタムテストランナーを指定します。

--testSequencer=<path>

独自のテストシーケンサーを指定します。 Please refer to the testSequencer configuration for details.

--testTimeout=<number>

テストのデフォルトのタイムアウト時間(ミリ秒)。 デフォルト値:5000。

--updateSnapshot

Alias: -u. テスト実行中に失敗した全てのスナップショットを再取得する場合にこのフラグを指定します。 Can be used together with a test suite pattern or with --testNamePattern to re-record snapshots.

--useStderr

各テストごとの結果をテストスイートの階層構造とともに表示します。

--verbose

各テストごとの結果をテストスイートの階層構造とともに表示します。

--version

Alias: -v. バージョンを表示して終了します。

--waitForUnhandledRejections

Gives one event loop turn to handle rejectionHandled, uncaughtException or unhandledRejection.

Without this flag Jest may report false-positive errors (e.g. actually handled rejection reported) or not report actually unhandled rejection (or report it for different test case).

This option may add a noticeable overhead for fast test suites.

--watch

ファイルの変更を監視し、そのファイルに関連するテストを再実行します。 If you want to re-run all tests when a file has changed, use the --watchAll option instead.

tip

Use --no-watch (or --watch=false) to explicitly disable the watch mode if it was enabled using --watch. In most CI environments, this is automatically handled for you.

--watchAll

ファイルを監視し、何らかの変更があった場合に全テストを再実行します。 If you want to re-run only the tests that depend on the changed files, use the --watch option.

tip

Use --no-watchAll (or --watchAll=false) to explicitly disable the watch mode if it was enabled using --watchAll. In most CI environments, this is automatically handled for you.

--watchman

Whether to use watchman for file crawling. Defaults to true. Disable using --no-watchman.

--workerThreads

Whether to use worker threads for parallelization. Child processes are used by default.

caution

This is experimental feature. See the workerThreads configuration option for more details.