Configuring Jest
Jestの設定は、プロジェクトの package.json
ファイルか、 jest.config.js
ファイルまたは --config <path/to/js|json>
オプションから、定義することができます。 package.json
に Jest の構成を保存したい場合は、Jest が設定を見つけられるように "jest" キーをトップレベルに設定しなければなりません。
{
"name": "my-project",
"jest": {
"verbose": true
}
}
またはJavaScriptファイルで
// jest.config.js
module.exports = {
verbose: true,
};
出力される構成はJSON形式でシリアライズできなければならないことに留意して下さい。
--config
オプションを使用した場合、JSON ファイルには "jest" キーを含んではいけません。
{
"bail": 1,
"verbose": true
}
オプション
These options let you control Jest's behavior in your package.json
file. The Jest philosophy is to work great by default, but sometimes you just need more configuration power.
デフォルト
Jest のデフォルトオプションを取得して、必要に応じて展開することができます。
// jest.config.js
const {defaults} = require('jest-config');
module.exports = {
// ...
moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
// ...
};
<autogenerated_table_of_contents>
リファレンス
automock
[boolean]
デフォルト: false
This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface.
例:
// utils.js
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
//__tests__/automocking.test.js
import utils from '../utils';
test('if utils mocked automatically', () => {
// Public methods of `utils` are now mock functions
expect(utils.authorize.mock).toBeTruthy();
expect(utils.isAuthorized.mock).toBeTruthy();
// You can provide them with your own implementation
// or just pass the expected return value
utils.authorize.mockReturnValue('mocked_token');
utils.isAuthorized.mockReturnValue(true);
expect(utils.authorize()).toBe('mocked_token');
expect(utils.isAuthorized('not_wizard')).toBeTruthy();
});
Note: Core modules, like fs
, are not mocked by default. They can be mocked explicitly, like jest.mock('fs')
.
Note: Automocking has a performance cost most noticeable in large projects. See here for details and a workaround.
bail
[number | boolean]
Default: 0
By default, Jest runs all tests and produces all errors into the console upon completion. The bail config option can be used here to have Jest stop running tests after n
failures. Setting bail to true
is the same as setting bail to 1
.
browser
[boolean]
デフォルト: false
モジュールの依存関係を解決する際に package.json
内に記述されたBrowserifyの "browser"
フィールドを優先します。 一部のモジュールはNode上で動作しているかブラウザ上で動作しているかによって異なるバージョンを出力します。
cacheDirectory
[string]
デフォルト: "/tmp/<path>"
Jestがキャッシュする依存情報を格納するディレクトリを指定します。
Jestはテスト実行中に必要となるかもしれないファイルシステムを集めやすくするため、依存関係のツリーを一度(前もって) 読み込んでキャッシュします。 この設定オプションによりJestがディスク上にキャッシュを格納する場所を指定できます。
clearMocks
[boolean]
デフォルト: false
各テストごとに自動的にモックコールとモックインスタンスをクリアします。 各テスト間でjest.clearAllMocks()
を呼び出すのと同じです。 このオプションは与えられたモックの実装を削除することはしません。
collectCoverage
[boolean]
デフォルト: false
テスト実行中にカバレッジ情報を取得するかどうかを指定します。 カバレッジ取得を指定して実行される全てのファイルについて書き換えるので、テストが大幅に遅くなることがあります。
collectCoverageFrom
[array]
デフォルト: undefined
カバレッジ情報を取得する対象のファイルを指定する globパターンの配列を設定します。 ファイルが指定されたglobパターンに一致すれば、ファイルにテストが存在せずテストスイートが必要としないファイルであってもカバレッジ情報を収集します。
例:
{
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/vendor/**"
]
}
上記の設定ではプロジェクトの rootDir
配下の**/node_modules/**
または**/vendor/**
に一致するものを除いたすべてのファイルからカバレッジ情報を取得します。
注意: このオプションを使用するにはcollectCoverage
パラメータがtrueに設定されているか--coverage
オプションを付けてjestを実行する必要があります。
Help:
If you are seeing coverage output such as...
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
================================================================================
Jest: Coverage data for global was not found.
Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory
[string]
デフォルト: undefined
カバレッジ情報を出力するファイルを格納するディレクトリを指定します。
coveragePathIgnorePatterns
[配列]
デフォルト: ["/node_modules/"]
An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped.
パターン文字列はフルパスに対して照合されます。 <rootDir>
文字列トークンをプロジェクトのルートディレクトリとして指定することで、異なるルートディレクトリを持ちうる異なる環境のファイルを誤って無視してしまうことを防ぐことができます。 例: ["<rootDir>/build/", "<rootDir>/node_modules/"]
。
coverageReporters
[配列]
Default: ["json", "lcov", "text", "clover"]
カバレッジリポートを出力する際に Jest が使用するリポータのリストです。 任意の istanbul reporter が使用できます。
Note: Setting this option overwrites the default values. Add "text"
or "text-summary"
to see a coverage summary in the console output.
coverageThreshold
[object]
デフォルト: undefined
このオプションはカバレッジ取得結果の最小しきい値を強制的に設定します。 しきい値は、 global
、 glob およびディレクトリもしくはファイルパスを指定できます。 しきい値に到達しなかった場合、Jest はテストが失敗したと判定します。 正の値で指定されたしきい値を、最小限求められるカバレッジのパーセンテージとして設定します。 負のしきい値を設定することで、カバーされなかった部分の最大許容量を指定します。
たとえば、以下の設定では、ブランチ、行、関数でカバレッジが 80% を下回るものがあるか、または 10 個以上のステートメントがカバーされていなかった場合、Jest はテストが失敗したと判定します。
{
...
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
}
}
もし glob またはパスが global
として指定されていれば、一致したパスのカバレッジデータは全体のカバレッジからは除外され、独自のしきい値が適用されます。 glob へのしきい値はその globs と一致する全てのファイルに適用されます。 指定されたパスのファイルが見つからない場合は、エラーが返されます。
例えば、以下の設定では:
{
...
"jest": {
"coverageThreshold": {
"global": {
"branches": 50,
"functions": 50,
"lines": 50,
"statements": 50
},
"./src/components/": {
"branches": 40,
"statements": 40
},
"./src/reducers/**/*.js": {
"statements": 90
},
"./src/api/very-important-module.js": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
}
}
}
Jest は以下の状況ではテストが失敗したと判断します:
./src/components
ディレクトリで、ブランチまたはステートメントのカバレッジが 40% 未満。./src/reducers/**/*.js
のglob表現に一致するファイルの1つのカバレッジが 90% 未満。./src/api/very-important-module.js
ファイルのカバレッジが 100% 未満。- 残りのファイルのカバレッジが 50% 未満 (
global
で設定)。
dependencyExtractor
[string]
デフォルト: undefined
This option allows the use of a custom dependency extractor. It must be a node module that exports an object with an extract
function. E.g.:
const fs = require('fs');
const crypto = require('crypto');
module.exports = {
extract(code, filePath, defaultExtract) {
const deps = defaultExtract(code, filePath);
// Scan the file and add dependencies in `deps` (which is a `Set`)
return deps;
},
getCacheKey() {
return crypto
.createHash('md5')
.update(fs.readFileSync(__filename))
.digest('hex');
},
};
The extract
function should return an iterable (Array
, Set
, etc.) with the dependencies found in the code.
That module can also contain a getCacheKey
function to generate a cache key to determine if the logic has changed and any cached artifacts relying on it should be discarded.
errorOnDeprecated
[boolean]
デフォルト: false
Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.
extraGlobals
[配列]
デフォルト: undefined
Test files run inside a vm, which slows calls to global context properties (e.g. Math
). With this option you can specify extra properties to be defined inside the vm for faster lookups.
For example, if your tests call Math
often, you can pass it by setting extraGlobals
.
{
...
"jest": {
"extraGlobals": ["Math"]
}
}
forceCoverageMatch
[配列]
デフォルト: ['']
Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage.
たとえば、次のような .t.js
拡張子を持つソースファイルがある時、
// sum.t.js
export function sum(a, b) {
return a + b;
}
if (process.env.NODE_ENV === 'test') {
test('sum', () => {
expect(sum(1, 2)).toBe(3);
});
}
forceCoverageMatch
を設定することで、これらのファイルからカバレッジを集めることができます。
{
...
"jest": {
"forceCoverageMatch": ["**/*.t.js"]
}
}
globals
[object]
デフォルト: {}
全テスト環境で利用できるグローバル変数の配列を指定します。
例えば、下記の設定はグローバル変数 __DEV__
は全てのテスト環境において true
となります。
{
...
"jest": {
"globals": {
"__DEV__": true
}
}
}
(オブジェクトや配列のような)グローバル参照値を指定して一部のコードでテスト中にその値に変更を加える場合は、その変更は異なるテストファイルで実行されるテスト間で保存されない ことに注意して下さい。 さらに、globals
オブジェクトは json シリアライズ可能でなければならないため、グローバルな関数を指定することはできません。 そのためには、setupFiles
を使用します。
globalSetup
[string]
デフォルト: undefined
このオプションでは、カスタムのグローバルセットアップモジュールを指定することができます。モジュールでは、すべてのテストスイーツの前に一度だけトリガされる非同期関数をエクスポートします。 This function gets Jest's globalConfig
object as a parameter.
Note: A global setup module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
Note: Any global variables that are defined through globalSetup
can only be read in globalTeardown
. You cannot retrieve globals defined here in your test suites.
Note: While code transformation is applied to the linked setup-file, Jest will not transform any code in node_modules
. This is due to the need to load the actual transformers (e.g. babel
or typescript
) to perform transformation.
例:
// setup.js
module.exports = async () => {
// ...
// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
};
// teardown.js
module.exports = async function() {
await global.__MONGOD__.stop();
};
globalTeardown
[string]
デフォルト: undefined
このオプションでは、カスタムのグローバルティアダウンモジュールを指定することができます。モジュールでは、すべてのテストスイーツの後に一度だけトリガされる非同期関数をエクスポートします。 This function gets Jest's globalConfig
object as a parameter.
Note: A global teardown module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
_Node: The same caveat concerning transformation of node_modules_ as for
globalSetupapplies to
globalTeardown`.
maxConcurrency
[number]
Default: 5
A number limiting the number of tests that are allowed to run at the same time when using test.concurrent
. Any test above this limit will be queued and executed once a slot is released.
moduleDirectories
[配列]
デフォルト: ["node_modules"]
必要なモジュールの格納場所から上方向に再帰的に探索を行うディレクトリ名の配列を指定します。 このオプションを指定することで既定値が上書きされるため、 node_modules
内でパッケージの探索を行いたい場合は、他のオプションに加えて次の配列を追加して下さい: ["node_modules", "bower_components"]
moduleFileExtensions
[配列]
Default: ["js", "json", "jsx", "ts", "tsx", "node"]
An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for, in left-to-right order.
We recommend placing the extensions most commonly used in your project on the left, so if you are using TypeScript, you may want to consider moving "ts" and/or "tsx" to the beginning of the array.
moduleNameMapper
[object<string, string>]
デフォルト: null
単一のモジュールで画像やスタイルのようなリソースをスタブさせるために利用する正規表現パターンからモジュール名へのマップを指定します。
別名にマップされているモジュールはデフォルトでは自動モック機能が有効かどうかに関わらずモックされません。
ファイルパスでrootDir
を使いたい場合は、<rootDir>
文字列トークンを設定して下さい。
加えて、正規表現によりキャプチャした文字列を数字付きの後方参照を使って代入することができます。
例:
{
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
"module_name_(.*)": "<rootDir>/substituted_module_$1.js"
}
}
The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first.
注意: モジュール名を 正規表現^$
による境界なしでモジュール名を指定するとエラーの特定が困難となることがあります。 例えば relay
という表現では relay
を名前に含む全てのモジュール名の置換を行います: relay
, react-relay
そして graphql-relay
の全てが指定したスタブに置き換わります。
modulePathIgnorePatterns
[配列]
デフォルト: []
モジュールローダーから'見える'状態となる前に全てのモジュールパスに対して照合する正規表現の文字列の配列を指定します。 与えられたモジュールのパスがこの正規表現に一致した場合、テスト環境では当該モジュールはrequire()
できなくなります。
パターン文字列はフルパスに対して照合されます。 <rootDir>
文字列トークンをプロジェクトのルートディレクトリとして指定することで、異なるルートディレクトリを持ちうる異なる環境のファイルを誤って無視してしまうことを防ぐことができます。 例: [「< rootDir > ビルド/」]
。
modulePaths
[配列]
デフォルト: []
NODE_PATH
環境変数を設定する代わりの API として、modulePaths
にはモジュールの依存関係の解決を行う際の追加のロケーションの絶対パスの配列を指定します。 プロジェクトのルートディレクトリへのパスを指定するには<rootDir>
文字列トークンを使用して下さい。 例: ["<rootDir>/app/"]
。
notify
[boolean]
デフォルト: false
テスト結果の通知機能を有効にします。
notifyMode
[string]
Default: failure-change
Specifies notification mode. Requires notify: true
.
モード
always
: 常に通知を送ります。failure
: テストが失敗した場合に通知を送ります。success
: テストが成功した場合に通知を送ります。change
: ステータスが変化した場合に通知を送ります。success-change
: テストが成功したか、一度失敗した場合に通知を送ります。failure-change
: send a notification when tests fail or once when it passes.
preset
[string]
デフォルト: undefined
A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a jest-preset.json
or jest-preset.js
file at the root.
For example, this preset foo-bar/jest-preset.js
will be configured as follows:
{
"preset": "foo-bar"
}
プリセットは、ファイルシステムの相対パスで指定することも可能です。
{
"preset": "./node_modules/foo-bar/jest-preset.js"
}
prettierPath
[string]
Default: 'prettier'
Sets the path to the prettier
node module used to update inline snapshots.
projects
[配列<string | projectconfig>]
デフォルト: undefined
projects
設定がパスやglobパターンの配列で与えられた場合、Jestは指定されたプロジェクト全てで同時にテストを実行します。 このオプションはmonorepo構成のプロジェクトや同時に複数のプロジェクトに従事している時に効果を発揮します。
{
"projects": ["<rootDir>", "<rootDir>/examples/*"]
}
This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance.
プロジェクト機能は、複数の設定や複数のランナーを走らせるためにも使用できます。 この目的のために、設定オブジェクトの配列を渡すことができます。 たとえば、テストと ESLint (via jest-runner-eslint) の両方を Jest の同じ呼び出しで実行するには、次のような設定を書きます。
{
"projects": [
{
"displayName": "test"
},
{
"displayName": "lint",
"runner": "jest-runner-eslint",
"testMatch": ["<rootDir>/**/*.js"]
}
]
}
Note: When using multi project runner, it's recommended to add a displayName
for each project. This will show the displayName
of a project next to its tests.
reporters
[配列<modulename | [modulename, options]>]
デフォルト: undefined
Jestにカスタムレポーターを追加するにはこの設定オプションを指定します。 カスタムレポーターは、 onRunStart
、onTestStart
、onTestResult
、 onRunComplete
メソッドを実装したクラスであり、各イベントが発生した場合にこれらのメソッドが呼ばれます。
If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, default
can be passed as a module name.
以下の設定はデフォルトのレポーターを上書きします。
{
"reporters": ["<rootDir>/my-custom-reporter.js"]
}
以下の設定はJestが提供するデフォルトのレポーターに加えてカスタムレポーターを使用します。
{
"reporters": ["default", "<rootDir>/my-custom-reporter.js"]
}
加えて、カスタムレポーターは第2引数にoptions
オプションを渡すことで設定を行うことができます。
{
"reporters": [
"default",
["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
]
}
カスタムレポーターのモジュールはコンストラクタ引数にGlobalConfig
とレポーターオプションをとるクラスとして定義されなければなりません。
レポーターの例:
// my-custom-reporter.js
class MyCustomReporter {
constructor(globalConfig, options) {
this._globalConfig = globalConfig;
this._options = options;
}
onRunComplete(contexts, results) {
console.log('Custom reporter output:');
console.log('GlobalConfig: ', this._globalConfig);
console.log('Options: ', this._options);
}
}
module.exports = MyCustomReporter;
カスタムレポーターはgetLastError()
メソッドでエラーを返すことでJestを0でない戻り値で終了させることができます。
class MyCustomReporter {
// ...
getLastError() {
if (this._shouldFail) {
return new Error('my-custom-reporter.js reported an error');
}
}
}
全てのメソッドと引数の型を確認するには、types/TestRunner.js内の Reporter
typeを参照して下さい。
resetMocks
[boolean]
デフォルト: false
各テストごとに自動的にモックの状態をリセットします。 各テストの間で jest.resetAllMocks()
を実行するのと同じです。 このオプションはあらゆるモックに見せかけの実装を削除させますが、モックを最初の時点の実装に戻すものではありません。
resetModules
[boolean]
デフォルト: false
By default, each test file gets its own independent module registry. Enabling resetModules
goes a step further and resets the module registry before running each individual test. このオプションはテスト間のローカルのモジュールの状態が競合しないように各テストで使うモジュールを切り離したい場合に便利です。 プログラム内で jest.resetModules()
を利用することでも同様のことができます。
resolver
[string]
デフォルト: undefined
カスタムのリゾルバを利用する場合はこのオプションを指定します。 このリゾルバは、第1引数に依存関係の解決に用いるパスの文字列を、第2引数に以下の構造のオブジェクトを受け取る関数をエクスポートするnodeモジュールでなければなりません:
{
"basedir": string,
"browser": bool,
"extensions": [string],
"moduleDirectory": [string],
"paths": [string],
"rootDir": [string]
}
関数は解決されるべきモジュールへのパスかモジュールが見つからなければエラーを返します。
restoreMocks
[boolean]
デフォルト: false
各テストごとにモックの状態を自動的に復元します。 各テスト間でjest.restoreAllMocks()
を呼び出すのと同じです。 このオプションを指定することで、あらゆるモックに見せかけの実装を削除させ、モックを最初の時点の実装に戻させることができます。
rootDir
[string]
デフォルト: 設定ファイルまたは package.json
を含むルートディレクトリ。あるいは、もし package.json
が見つからなければ、pwd
の結果を設定します。
Jestがテストとモジュールをその範囲内で探索するルートディレクトリを指定します。 package.json
にJestの設定を記述してルートディレクトリをリポジトリのルートをしたい場合、この設定のパラメータ値はデフォルトのpackage.json
が格納されているディレクトリとなります。
多くの場合、リポジトリのどこにソースコードを格納するかによって、 'src'
または 'lib'
に設定されるでしょう。
パスを指定する他のオプションで'<rootDir>'
を文字列トークンとして利用する場合は、このオプションの値を参照することに注意して下さい。 このため、例えばsetupFiles
オプションのエントリポイントをルートディレクトリ直下の env-setup.js
ファイルとしたい場合は、このオプションの値は ["<rootDir>/env-setup.js"]
となるでしょう。
roots
[配列]
デフォルト: ["<rootDir>"]
Jestがその中でファイルを探索するのに使用するディレクトリのパスを使用します。
Jestに単一のサブディレクトリのみを探索させ(リポジトリ内にsrc/
ディレクトリがあるなど)、リポジトリの残りの場所にはアクセスさせたくない場合に有用です。
注意: rootDir
が他の設定オプションで再利用されるトークンとして最も頻繁に使われる一方で、roots
はJestの内部でテストファイルやソースコードファイルを見つけるのに使われます。 これは node_modules
から手動モック用にモジュールを見つける際にも適用されます(__mocks__
も roots
の中にある必要があります)。
注意: デフォルトでは、 roots
は <rootDir>
のみをエントリとして持ちますが、1つのプロジェクトで複数の roots を設定したい場合は、例えば次のように設定します: roots: ["<rootDir>/src/", "<rootDir>/tests/"]
。
runner
[string]
デフォルト: "jest-runner"
This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include:
Note: The runner
property value can omit the jest-runner-
prefix of the package name.
テストランナーを書くには、コンストラクタに globalConfig
を取り、以下のシグネチャを持つ runTests
メソッドを定義したクラスをエクスポートします。
async runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>
テストランナーを並列ではなく直列に走らせるように制限する必要があれば、対象のクラスに isSerial
というプロパティを持たせ、true
にセットする必要があります。
setupFiles
[array]
デフォルト: []
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. 各テストは個々の環境でテストを実行するため、これらのスクリプトはテスト環境にてテストコードそれ自身の実行前に直ちに実行されます。
It's also worth noting that setupFiles
will execute before setupFilesAfterEnv
.
setupFilesAfterEnv
[array]
デフォルト: []
A list of paths to modules that run some code to configure or set up the testing framework before each test. setupFiles
で指定したスクリプトはテストフレームワークを環境にインストールする前に実行されるため、このオプションで指定したスクリプトファイルは環境にテストフレームワークがインストールされた直後のタイミングでコードを実行することができます。
If you want a path to be relative to the root directory of your project, please include <rootDir>
inside a path's string, like "<rootDir>/a-configs-folder"
.
例えばJestはjasmineのAPIにモンキーパッチを当てて動作するjasmine
のプラグインをいくつか提供しています。 If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in these modules.
Note: setupTestFrameworkScriptFile
is deprecated in favor of setupFilesAfterEnv
.
snapshotResolver
[string]
デフォルト: undefined
The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk.
Example snapshot resolver module:
module.exports = {
// resolves from test to snapshot path
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
// resolves from snapshot to test path
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath
.replace('__snapshots__', '__tests__')
.slice(0, -snapshotExtension.length),
// Example test path, used for preflight consistency check of the implementation above
testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};
snapshotSerializers
[配列]
デフォルト: []
Jestがスナップショットテストに利用するスナップショットのシリアライザーのモジュールのパスのリストを指定します。
Jest は組み込みの JavaScript 型、HTML 要素 (Jest バージョン20.0.0+)、ImmutableJS (Jest バージョン20.0.0+)、そして React 要素に対応したデフォルトのシリアライザーを備えています。 詳細については snapshot test tutorial を参照してください。
シリアライザー モジュールの例:
// my-serializer-module
module.exports = {
print(val, serialize, indent) {
return 'Pretty foo: ' + serialize(val.foo);
},
test(val) {
return val && val.hasOwnProperty('foo');
},
};
serialize
は既存のプラグインを利用して値をシリアライズする関数です。
my-serializer-module
をシリアライザーとして使用する場合は、下記のような設定になります。
{
...
"jest": {
"snapshotSerializers": ["my-serializer-module"]
}
}
最終的にテストは下記のようになります:
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
レンダリングされたスナップショット:
Pretty foo: Object {
"x": 1,
"y": 2,
}
シリアライザーの依存関係を暗黙的から明示的なものにするには、Jest の設定に snapshotSerializers
へのパスを追加する代わりに、expect.addSnapshotSerializer
を呼び出してテストファイルに対応するモジュールを追加することもできます。
testEnvironment
[string]
デフォルト: "jsdom"
テスト実行時に使用されるテスト環境を指定します。 Jestのデフォルトの環境は jsdomを経由したブラウザライクな環境です。 Node環境によるサービスを構築する場合は、 node
オプションを指定することでnodeライクな環境を代わりに使うことができます。
By adding a @jest-environment
docblock at the top of the file, you can specify another environment to be used for all tests in that file:
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
テスト環境のセットアップに使用する独自のモジュールを作成できます。 モジュールは、setup
、 teardown
および runScript
メソッドを持つクラスをエクスポートする必要があります。 You can also pass variables from this module to your test suites by assigning them to this.global
object – this will make them available in your test suites as global variables.
Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.
例:
// my-custom-environment
const NodeEnvironment = require('jest-environment-node');
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
this.testPath = context.testPath;
}
async setup() {
await super.setup();
await someSetupTasks(this.testPath);
this.global.someGlobalObject = createGlobalObject();
}
async teardown() {
this.global.someGlobalObject = destroyGlobalObject();
await someTeardownTasks();
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = CustomEnvironment;
// my-test-suite
let someGlobalObject;
beforeAll(() => {
someGlobalObject = global.someGlobalObject;
});
Note: Jest comes with JSDOM@11 by default. Due to JSDOM 12 and newer dropping support for Node 6, Jest is unable to upgrade for the time being. However, you can install a custom testEnvironment
with whichever version of JSDOM you want. E.g. jest-environment-jsdom-thirteen, which has JSDOM@13.
testEnvironmentOptions
[Object]
デフォルト: {}
testEnvironment
に渡されるテスト環境のオプションです。 The relevant options depend on the environment. For example you can override options given to jsdom such as {userAgent: "Agent/007"}
.
testMatch
[配列]
(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
)
テストファイルを検出するのにJestが使用するglobパターンを指定します。 By default it looks for .js
, .jsx
, .ts
and .tsx
files inside of __tests__
folders, as well as any files with a suffix of .test
or .spec
(e.g. Component.test.js
or Component.spec.js
). test.js
または spec.js
といったファイルについても同様に見つけます。
See the micromatch package for details of the patterns you can specify.
See also testRegex
[string | Array
testPathIgnorePatterns
[配列]
デフォルト: ["/node_modules/"]
An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped.
パターン文字列はフルパスに対して照合されます。 <rootDir>
文字列トークンをプロジェクトのルートディレクトリとして指定することで、異なるルートディレクトリを持ちうる異なる環境のファイルを誤って無視してしまうことを防ぐことができます。 例: ["<rootDir>/build/", "<rootDir>/node_modules/"]
。
testRegex
[string | Array]
Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
The pattern or patterns Jest uses to detect test files. By default it looks for .js
, .jsx
, .ts
and .tsx
files inside of __tests__
folders, as well as any files with a suffix of .test
or .spec
(e.g. Component.test.js
or Component.spec.js
). test.js
または spec.js
といったファイルについても同様に見つけます。 See also testMatch
[array
以下はデフォルトの正規表現を可視化したものです。
├── __tests__
│ └── component.spec.js # test
│ └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test
Note: testRegex
will try to detect test files using the absolute file path therefore having a folder with name that match it will run all the files as tests
testResultsProcessor
[string]
デフォルト: undefined
独自の results processor を利用する場合はこのオプションを指定します。 results processor は、以下の構造のオブジェクトを第一引数として期待する関数をエクスポートする node モジュールで、引数に取ったオブジェクトを返す必要があります:
{
"success": bool,
"startTime": epoch,
"numTotalTestSuites": number,
"numPassedTestSuites": number,
"numFailedTestSuites": number,
"numRuntimeErrorTestSuites": number,
"numTotalTests": number,
"numPassedTests": number,
"numFailedTests": number,
"numPendingTests": number,
"openHandles": Array<Error>,
"testResults": [{
"numFailingTests": number,
"numPassingTests": number,
"numPendingTests": number,
"testResults": [{
"title": string (message in it block),
"status": "failed" | "pending" | "passed",
"ancestorTitles": [string (message in describe blocks)],
"failureMessages": [string],
"numPassingAsserts": number,
"location": {
"column": number,
"line": number
}
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": absolute path to test file,
"coverage": {}
},
...
]
}
testRunner
[string]
デフォルト: jasmine2
This option allows use of a custom test runner. The default is jasmine2. A custom test runner can be provided by specifying a path to a test runner implementation.
テストランナーのモジュールは、下記のシグネチャを持つ関数をエクスポートしなければなりません:
function testRunner(
config: Config,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
このような関数の例は、デフォルトの jasmine2 test runner packageで確認できます。
testURL
[string]
Default: http://localhost
This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
.
timers
[string]
デフォルト: real
この値を fake
に設定することで、setTimeout
などの関数に対して偽のタイマーを使用することができます。 偽のタイマーはテストでは待ちたくないような長いタイムアウト時間を設定するようなコードがある時に役立ちます。
transform
[object<string, string>]
デフォルト: undefined
正規表現からtransformerへのパスへのマップを指定します。 transformerはソースファイルを変換する同期処理を行う関数を提供するモジュールです。 例えばまだnodeではサポートされていない新しい言語の機能をモジュールやテストで使用したい時、将来のJavaScriptのバージョンを現在のものに変換する多くのコンパイラの中の1つをプラグインとして利用するでしょう。 例: examples/typescript の例や webpack tutorial を参照してください。
このようなコンパイラの例には、babel、 typescript、や async-to-gen が含まれます。
Note: a transformer is only run once per file unless the file has changed. During development of a transformer it can be useful to run Jest with --no-cache
to frequently delete Jest's cache.
注意: babel-jest
transformerを使用しながら追加でコードのプリプロセッサを使用したい場合は、何らかの方法で "transform" フィールドが上書きされるとbabel-jest
は自動的には読み込まれなってしまうことに注意して下さい。 JavaScriptコードのコンパイルにbabel-jest
を使用したい場合は明示的に定義されなければなりません。 babel-jest pluginを参照して下さい。
transformIgnorePatterns
[配列]
デフォルト: ["/node_modules/"]
An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed.
パターン文字列はフルパスに対して照合されます。 <rootDir>
文字列トークンをプロジェクトのルートディレクトリとして指定することで、異なるルートディレクトリを持ちうる異なる環境のファイルを誤って無視してしまうことを防ぐことができます。
例:["<rootDir>/bower_components/", "<rootDir>/node_modules/"]
。
Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules
are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns
to whitelist such modules. You'll find a good example of this use case in React Native Guide.
unmockedModulePathPatterns
[配列]
デフォルト: []
モジュールローダーが自動的にモック返す前に全てのモジュールに対して照合する正規表現パターンの配列を指定します。 モジュールのパスがリスト中のいずれかのパターンにマッチした場合、モジュールローダーによる自動的なモック化は行われません。
このオプションは(underscore/lo-dashなどのような) ほぼ常にプライベートな処理の実装には、ほぼいつも利用される一般的に'ユーティリティ' モジュールに関して役に立ちます。 出来るだけこのリストを小さく保ち、個々のテスト内でjest.mock()
/jest.unmock()
を常に明示的に使用することが大抵の場合でベストプラクティスとなります。 明示的にテスト前にセットアップを行うことで、テストを読む他の人がそのテストがなぜその環境で実行されるのかを理解するのがとても簡単にになります。
個々のテストにおいて、テストファイルの先頭でjest.mock()
を明示的に呼び出す事でこの設定を上書きすることが可能です。
verbose
[boolean]
デフォルト: false
Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution.
watchPathIgnorePatterns
[配列]
デフォルト: []
ウォッチモードでテストを再実行する前に、全てのソースファイルのパスと照合させる正規表現パターンの配列です。 ファイルのパスがパターンのどれかに一致していれば、ファイルが更新された際にテストを再実行しません。
正規表現パターンはフルパスに対して照合されます。 <rootDir>
文字列トークンをプロジェクトのルートディレクトリとして指定することで、異なるルートディレクトリを持ちうる異なる環境のファイルを誤って無視してしまうことを防ぐことができます。 例: ["<rootDir>/node_modules/"]
watchPlugins
[配列<string | [string, object]>]
デフォルト: []
This option allows you to use a custom watch plugins. Read more about watch plugins here.
Examples of watch plugins include:
jest-watch-master
jest-watch-select-projects
jest-watch-suspend
jest-watch-typeahead
jest-watch-yarn-workspaces
Note: The values in the watchPlugins
property value can omit the jest-watch-
prefix of the package name.
//
[string]
No default
This option allow comments in package.json
. Include the comment text as the value of this key anywhere in package.json
.
例:
{
"name": "my-project",
"jest": {
"//": "Comment goes here",
"verbose": true
}
}