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

Jest CLI オプション

jest のコマンドラインランナーは多くの便利なオプションを持っています。 jest --help を実行することで使用可能な全てのオプションを見ることができます。 以下に示すオプションの多くは任意のテストを実行する際に利用できます。 Jest の各設定オプションは CLI 経由で指定できます。

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

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

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

jest

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

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

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

jest -o

path/to/fileA.jspath/to/fileB.js に関連したテストを実行する:

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

スペック名に一致するテストを実行する (基本的には describe または test 内にある名前との一致を確認する):

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"

キャメルケースとダッシュ区切りの引数のサポート

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

jest --collect-coverage
jest --collectCoverage

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

jest --update-snapshot --detectOpenHandles

オプション

note

CLI のオプションは Configuration の設定値に優先します。


リファレンス

jest <regexForTestFiles>

引数を付けて jestコマンドを実行した場合、その引数はプロジェクト配下のファイルを照合する正規表現として扱われます。 パターンを与えてテストスイートを実行することができます。 パターンに一致するファイルだけが選択され、実行されます。 端末によっては、次のように引数をクオートで囲む必要がある場合があります。 On Windows, you will need to use / as a path separator or escape \ as \\.

--bail[=<n>]

エイリアス: -b。 失敗したテストスイートの数 n 回に達した場合に直ちにテストスイートを終了します。 デフォルトの回数は 1 です。

--cache

キャッシュを使用するかを指定します。 既定値ではtrueです。 キャッシュを無効化するには --no-cacheを指定します。

caution

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

キャッシュの内容を調べるには、 --showConfig を使用して、 cacheDirectory を確認してください。 キャッシュをクリアする必要がある場合は、--clearCache を使用してください。

--changedFilesWithAncestor

現在の変更と最後のコミットによる変更に関係するテストを実行します。 --onlyChanged と同様に動作します。

--changedSince

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

--ci

このオプションが指定された場合、Jestは CI 環境で実行されていると仮定します。 これによって、新しいスナップショットが見つかったときの挙動が変わります。 自動的に新しいスナップショットを保存する通常の動作ではなく、テストを失敗させてJestに --updateSnapshotオプションを指定するように要求します。

--clearCache

Jest のキャッシュディレクトリを削除し、テストを実行せずに終了します。 Jest のデフォルトのキャッシュディレクトリか、もしくはオプションが渡された場合は cacheDirectory を削除します。 デフォルトのキャッシュディレクトリは 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

代わりに、環境変数 FORCE_COLOR=true を設定して強制的に有効にしたり、FORCE_COLOR=false でカラー出力を無効化することもできます。 FORCE_COLOR を使用すると、他のすべてのカラーサポートチェックが上書きされます。

--config=<path>

別名: -c。 テストの探索と実行の方法を指定する Jest の設定ファイルのパスを引数に指定します。 設定ファイルにrootDirが設定されていなければ、コンフィグファイルのあるディレクトリをプロジェクトのrootDirと推定します。 引数にJSON形式の値を与えることでもJestは設定として使用します。

--coverage[=<boolean>]

エイリアス: --collectCoverage。 テストのカバレッジ情報が収集され出力に表示されるべきであることを指定します。 <boolean> の値により設定オプションを上書きします。

--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 が何も出力せずに終了するのを防ぐことができます。 Jest を終了させるために --forceExit を使用する必要がある場合、潜在的な原因を追跡する際に、このオプションを使用してください。 これは --runInBandを意味し、テストを連続して実行させます。 async_hooks を使用して実装されました。 このオプションには重大なパフォーマンスの低下があり、デバッグにのみ使用する必要があります。

--env=<environment>

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

--errorOnDeprecated

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

--expand

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

--filter=<file>

Path to a module exporting a filtering function. この非同期関数は、{ filtered: Array<{ test: string }> } を持つオブジェクトを返すことで、テストを除外するように操作できるテストパスのリストを受け取ります。 特に、既知の壊れたテストをフィルタリングするためのテストインフラストラクチャと組み合わせて使用する場合に便利です。例えば、次のように使います。

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

return {
filtered: allowedPaths,
};
};

--findRelatedTests <spaceSeparatedListOfSourceFiles>

引数で渡された、スペース区切りのソースリストにあるテストを探して実行します。 コミット前に最小限必要なテストを実行するフックで使うのに便利です。 ソースファイルのテストカバレッジを含めるのに、--coverageが使用でき、--collectCoverageFrom でファイルを重複して指定する必要はありません。

--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 は各プロジェクトを識別するために、設定内の属性 displayName を利用します。 このオプションを使用する場合は、すべてのプロジェクトに displayName を指定してください。

--init

基本の設定ファイルを生成する. 次のコマンドを実行すると、Jest はあなたのプロジェクトの構成に基づいたいくつかの質問をし、各オプションの短い説明を含む jest.config.js ファイルを生成します。

--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

最後に行ったコミットによるファイル変更に関係するテストをすべて実行します。 --onlyChanged と同様に動作します。

--listTests

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

--logHeapUsage

各テスト後にヒープ使用率を記録します。 メモリリークのデバッグに役立ちます。 nodeで-runInBand--expose-gcを指定して一緒に使用して下さい。

--maxConcurrency=<num>

テストの同時実行数の最大値を設定します。 test.concurrent を使用するテストにのみ影響します。

--maxWorkers=<num>|<string>

別名: -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

テスト結果の通知を有効にします。 JavaScriptのテスト以外の何かに意識を集中させてしまいたくない場合に適しています。

--onlyChanged

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

--outputFile=<filename>

--jsonが同時に指定された場合にテスト結果をファイルに出力します。 得られる JSON の構造は 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.

--reporters

指定されたレポーターでテストを実行します。 リポーターオプション は 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

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

--runTestsByPath

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

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.

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

Run the tests of the specified projects. Jest は各プロジェクトを識別するために、設定内の属性 displayName を利用します。 このオプションを使用する場合は、すべてのプロジェクトに displayName を指定してください。

--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

location 項目をテスト結果に追加します。 レポーターでテストの場所を表示したい場合に役立ちます。

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>

別名: -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 --testPathPattern, 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.

--testPathPattern=<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

別名: -u。 テスト実行中に失敗した全てのスナップショットを再取得する場合にこのフラグを指定します。 スナップショットを再取得するためにテストスイートのファイル名のパターンや --testNamePatternオプションを同時に利用することができます。

--useStderr

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

--verbose

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

--version

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

--watch

ファイルの変更を監視し、そのファイルに関連するテストを再実行します。 ファイル変更時に全テストを再実行したい場合は、 --watchAllオプションを指定して下さい。

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

ファイルを監視し、何らかの変更があった場合に全テストを再実行します。 変更されたファイルに依存するテストのみ再実行したい場合は、--watchオプションを指定して下さい。

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

ウォッチマン をファイルクロールに使用するかどうか。 デフォルトは true です。 --no-watchman で無効になります。