Jest の設定
Jest の理念は、デフォルトで優れた動作をすることです。しかし、より高度な設定が必要になる場合があります。
専用の JavaScript、TypeScript、または JSON ファイルに設定を定義することをお勧めします。ファイル名が `jest.config.js|ts|mjs|cjs|json` の場合、自動的に検出されます。 `--config` フラグを使用して、ファイルへの明示的なパスを渡すことができます。
結果として得られる設定オブジェクトは、常に JSON シリアライズ可能である必要があることに注意してください。
設定ファイルは、オブジェクトをエクスポートする必要があります。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
verbose: true,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
または、オブジェクトを返す関数
- JavaScript
- TypeScript
/** @returns {Promise<import('jest').Config>} */
module.exports = async () => {
return {
verbose: true,
};
};
import type {Config} from 'jest';
export default async (): Promise<Config> => {
return {
verbose: true,
};
};
TypeScript 設定ファイルを読み取るには、`ts-node` が必要です。プロジェクトにインストールされていることを確認してください。
設定は、プレーンオブジェクトとして JSON ファイルにも保存できます。
{
"bail": 1,
"verbose": true
}
あるいは、Jest の設定はプロジェクトの `package.json` の `"jest"` キーを使用して定義することもできます。
{
"name": "my-project",
"jest": {
"verbose": true
}
}
オプション
必要に応じて拡張するために、`jest-config` から Jest のデフォルト値を取得できます。
- JavaScript
- TypeScript
const {defaults} = require('jest-config');
/** @type {import('jest').Config} */
const config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts', 'cts'],
};
module.exports = config;
import type {Config} from 'jest';
import {defaults} from 'jest-config';
const config: Config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts'],
};
export default config;
automock
[boolean]bail
[number | boolean]cacheDirectory
[string]clearMocks
[boolean]collectCoverage
[boolean]collectCoverageFrom
[array]coverageDirectory
[string]coveragePathIgnorePatterns
[array<string>]coverageProvider
[string]coverageReporters
[array<string | [string, options]>]coverageThreshold
[object]dependencyExtractor
[string]displayName
[string, object]errorOnDeprecated
[boolean]extensionsToTreatAsEsm
[array<string>]fakeTimers
[object]forceCoverageMatch
[array<string>]globals
[object]globalSetup
[string]globalTeardown
[string]haste
[object]injectGlobals
[boolean]maxConcurrency
[number]maxWorkers
[number | string]moduleDirectories
[array<string>]moduleFileExtensions
[array<string>]moduleNameMapper
[object<string, string | array<string>>]modulePathIgnorePatterns
[array<string>]modulePaths
[array<string>]notify
[boolean]notifyMode
[string]openHandlesTimeout
[number]preset
[string]prettierPath
[string]projects
[array<string | ProjectConfig>]randomize
[boolean]reporters
[array<moduleName | [moduleName, options]>]resetMocks
[boolean]resetModules
[boolean]resolver
[string]restoreMocks
[boolean]rootDir
[string]roots
[array<string>]runner
[string]sandboxInjectedGlobals
[array<string>]setupFiles
[array]setupFilesAfterEnv
[array]showSeed
[boolean]slowTestThreshold
[number]snapshotFormat
[object]snapshotResolver
[string]snapshotSerializers
[array<string>]testEnvironment
[string]testEnvironmentOptions
[Object]testFailureExitCode
[number]testMatch
[array<string>]testPathIgnorePatterns
[array<string>]testRegex
[string | array<string>]testResultsProcessor
[string]testRunner
[string]testSequencer
[string]testTimeout
[number]transform
[object<string, pathToTransformer | [pathToTransformer, object]>]transformIgnorePatterns
[array<string>]unmockedModulePathPatterns
[array<string>]verbose
[boolean]watchPathIgnorePatterns
[array<string>]watchPlugins
[array<string | [string, Object]>]watchman
[boolean]workerIdleMemoryLimit
[number|string]- //
workerThreads
参照
automock
[boolean]
デフォルト: `false`
このオプションは、テストでインポートされたすべてのモジュールを自動的にモックする必要があることを Jest に指示します。テストで使用されるすべてのモジュールには、代替実装があり、API サーフェスは維持されます。
例
export default {
authorize: () => 'token',
isAuthorized: secret => secret === 'wizard',
};
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 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();
});
手動でモックを作成した場合(例:`__mocks__/lodash.js`)、Node モジュールは自動的にモックされます。詳細はこちら。
`fs`のようなNode.jsのコアモジュールは、デフォルトではモックされません。`jest.mock('fs')`のように明示的にモックできます。
bail
[number | boolean]
デフォルト: `0`
デフォルトでは、Jest はすべてのテストを実行し、完了時にすべてのエラーをコンソールに出力します。`bail` 設定オプションを使用すると、`n` 回の失敗後に Jest がテストの実行を停止するようにできます。`bail` を `true` に設定することは、`bail` を `1` に設定することと同じです。
cacheDirectory
[string]
デフォルト: `/tmp/<path>`
Jest がキャッシュされた依存関係情報を保存するディレクトリ。
Jest は依存関係ツリーを一度(事前に)スキャンしてキャッシュしようとします。これにより、テスト実行中に発生する必要のあるファイルシステムの変更を軽減できます。この設定オプションを使用すると、Jest がそのキャッシュデータをディスク上に保存する場所をカスタマイズできます。
clearMocks
[boolean]
デフォルト: `false`
各テストの前に、モック呼び出し、インスタンス、コンテキスト、結果を自動的にクリアします。各テストの前に `jest.clearAllMocks()` を呼び出すことと同等です。これは、提供されている可能性のあるモック実装を削除しません。
collectCoverage
[boolean]
デフォルト: `false`
テストの実行中にカバレッジ情報を収集するかどうかを示します。これは実行されたすべてのファイルにカバレッジ収集ステートメントをレトロフィットするため、テストの速度が大幅に低下する可能性があります。
Jest には、`babel`(デフォルト)と `v8` の 2 つのカバレッジプロバイダーが付属しています。詳細については、`coverageProvider` オプションを参照してください。
`babel` と `v8` のカバレッジプロバイダーは、それぞれ `/* istanbul ignore next */` と `/* c8 ignore next */` のコメントを使用して、カバレッジレポートから行を除外します。詳細については、`istanbuljs` のドキュメント と `c8` のドキュメント を参照してください。
collectCoverageFrom
[array]
デフォルト: `undefined`
カバレッジ情報を収集するファイルのセットを示す、glob パターン の配列。ファイルが指定された glob パターンに一致する場合、そのファイルに対してテストが存在せず、テストスイートで必要とされない場合でも、そのファイルのカバレッジ情報が収集されます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
export default config;
これにより、`**/node_modules/**` または `**/vendor/**` に一致するものを除く、プロジェクトの `rootDir` 内のすべてのファイルについてカバレッジ情報が収集されます。
各 glob パターンは、設定で指定された順序で適用されます。たとえば、`["!**/__tests__/**", "**/*.js"]` は、否定が 2 番目のパターンで上書きされるため、`__tests__` を除外しません。この例で否定された glob を機能させるには、`**/*.js` の後に配置する必要があります。
このオプションには、`collectCoverage` を `true` に設定するか、`--coverage` を使用して Jest を呼び出す必要があります。
ヘルプ
次のようなカバレッジ出力が表示されている場合…
=============================== 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.
glob パターンがどのファイルにも一致していない可能性が最も高いです。glob が互換性があることを確認するには、micromatch のドキュメントを参照してください。
coverageDirectory
[string]
デフォルト: `undefined`
Jest がカバレッジファイルを書き出すディレクトリ。
coveragePathIgnorePatterns
[array<string>]
デフォルト: `["/node_modules/"]`
テスト実行前にすべてのファイルパスに照合される正規表現パターンの配列です。ファイルパスがこれらのパターンのいずれかに一致した場合、カバレッジ情報はスキップされます。
これらのパターン文字列は、完全パスに照合されます。プロジェクトのルートディレクトリへのパスを含めるには、<rootDir>
文字列トークンを使用してください。これにより、ルートディレクトリが異なる環境で誤ってすべてのファイルが無視されるのを防ぐことができます。例: ["<rootDir>/build/", "<rootDir>/node_modules/"]
。
coverageProvider
[文字列]
カバレッジのためにコードをインストルメントする際に使用するプロバイダーを示します。許容される値はbabel
(デフォルト)またはv8
です。
coverageReporters
[配列<文字列 | [文字列, オプション]>]
デフォルト: ["clover", "json", "lcov", "text"]
Jestがカバレッジレポートを作成する際に使用するレポーター名のリストです。任意のistanbulレポーターを使用できます。
このオプションを設定すると、デフォルト値が上書きされます。コンソール出力にカバレッジのサマリーを表示するには、"text"
または"text-summary"
を追加します。
タプル形式を使用して追加のオプションを渡すことができます。たとえば、完全に網羅されたすべてのファイルのカバレッジレポート行を非表示にすることができます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
export default config;
オプションオブジェクトの形状の詳細については、型定義のCoverageReporterWithOptions
型を参照してください。
coverageThreshold
[オブジェクト]
デフォルト: `undefined`
これは、カバレッジ結果の最小しきい値の適用を構成するために使用されます。しきい値は、global
として、globとして、ディレクトリまたはファイルパスとして指定できます。しきい値を満たしていない場合、jestは失敗します。正の数として指定されたしきい値は、必要な最小パーセンテージとみなされます。負の数として指定されたしきい値は、許容される未網羅エンティティの最大数を表します。
たとえば、次の構成では、ブランチ、行、関数のカバレッジが80%未満である場合、または10個を超える未網羅ステートメントがある場合、jestは失敗します。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
export default config;
globまたはパスをglobal
と一緒に指定した場合、一致するパスのカバレッジデータは全体のカバレッジから差し引かれ、しきい値は個別に適用されます。globのしきい値は、globと一致するすべてのファイルに適用されます。パスで指定されたファイルが見つからない場合、エラーが返されます。
たとえば、次の構成の場合
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
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,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
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,
},
},
};
export default config;
Jestは、次の場合に失敗します。
./src/components
ディレクトリのブランチまたはステートメントのカバレッジが40%未満の場合。./src/reducers/**/*.js
globと一致するファイルのいずれかのステートメントのカバレッジが90%未満の場合。./src/api/very-important-module.js
ファイルのカバレッジが100%未満の場合。- 残りのすべてのファイルの合計カバレッジが50%未満の場合(
global
)。
dependencyExtractor
[文字列]
デフォルト: `undefined`
このオプションでは、カスタム依存関係抽出器を使用できます。これは、extract
関数をエクスポートするオブジェクトをエクスポートするノードモジュールである必要があります。例:
const crypto = require('crypto');
const fs = require('fs');
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');
},
};
extract
関数は、コードで見つかった依存関係を含む反復可能オブジェクト(Array
、Set
など)を返す必要があります。
そのモジュールには、ロジックが変更されたかどうかを判断し、それに依存するキャッシュされたアーティファクトを破棄する必要があるかどうかを判断するためのキャッシュキーを生成するgetCacheKey
関数を含めることもできます。
displayName
[文字列、オブジェクト]
デフォルト: undefined
テスト実行中にテストと一緒にラベルを印刷できるようにします。これは、多くのjest設定ファイルが存在する可能性のあるマルチプロジェクトリポジトリでより役立ちます。これにより、テストがどのプロジェクトに属しているかを視覚的に確認できます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: 'CLIENT',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: 'CLIENT',
};
export default config;
または、name
プロパティとcolor
プロパティを持つオブジェクトを渡すことができます。これにより、displayName
の背景色のカスタム設定が可能になります。displayName
の値が文字列の場合、displayName
はデフォルトで白になります。Jestはchalk
を使用して色を提供します。そのため、chalk
でサポートされている色の有効なオプションはすべて、Jestでもサポートされています。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
export default config;
errorOnDeprecated
[ブール値]
デフォルト: `false`
非推奨APIを呼び出すと、役立つエラーメッセージがスローされます。アップグレードプロセスを容易にするのに役立ちます。
extensionsToTreatAsEsm
[配列<文字列>]
デフォルト: []
Jestは、最も近いpackage.json
のtype
フィールドがmodule
に設定されている.mjs
および.js
ファイルをECMAScriptモジュールとして実行します。ネイティブESMで実行する必要がある他のファイルがある場合は、ここでそのファイル拡張子を指定する必要があります。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
extensionsToTreatAsEsm: ['.ts'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
extensionsToTreatAsEsm: ['.ts'],
};
export default config;
JestのESMサポートはまだ実験的です。詳細については、そのドキュメントを参照してください。
fakeTimers
[オブジェクト]
デフォルト: {}
コードの一部で長いタイムアウトを設定し、テストで待機したくない場合に、フェイクタイマーが役立つ場合があります。詳細については、フェイクタイマーガイドおよびAPIドキュメントを参照してください。
このオプションは、すべてのテストのフェイクタイマーのデフォルト構成を提供します。テストファイルでjest.useFakeTimers()
を呼び出すと、これらのオプションが使用されるか、構成オブジェクトを渡すと上書きされます。たとえば、process.nextTick()
の元の実装を維持し、実行される再帰的タイマーの制限を調整するようにJestに指示できます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
export default config;
// install fake timers for this file using the options from Jest configuration
jest.useFakeTimers();
test('increase the limit of recursive timers for this and following tests', () => {
jest.useFakeTimers({timerLimit: 5000});
// ...
});
各テストファイルにjest.useFakeTimers()
を含める代わりに、Jest設定ですべてのテストでフェイクタイマーをグローバルに有効にできます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
},
};
export default config;
構成オプション
type FakeableAPI =
| 'Date'
| 'hrtime'
| 'nextTick'
| 'performance'
| 'queueMicrotask'
| 'requestAnimationFrame'
| 'cancelAnimationFrame'
| 'requestIdleCallback'
| 'cancelIdleCallback'
| 'setImmediate'
| 'clearImmediate'
| 'setInterval'
| 'clearInterval'
| 'setTimeout'
| 'clearTimeout';
type ModernFakeTimersConfig = {
/**
* If set to `true` all timers will be advanced automatically by 20 milliseconds
* every 20 milliseconds. A custom time delta may be provided by passing a number.
* The default is `false`.
*/
advanceTimers?: boolean | number;
/**
* List of names of APIs that should not be faked. The default is `[]`, meaning
* all APIs are faked.
*/
doNotFake?: Array<FakeableAPI>;
/** Whether fake timers should be enabled for all test files. The default is `false`. */
enableGlobally?: boolean;
/**
* Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.
* The default is `false`.
*/
legacyFakeTimers?: boolean;
/** Sets current system time to be used by fake timers, in milliseconds. The default is `Date.now()`. */
now?: number;
/** Maximum number of recursive timers that will be run. The default is `100_000` timers. */
timerLimit?: number;
};
何らかの理由で、レガシー実装のフェイクタイマーを使用する必要がある場合があります。グローバルに有効にする方法は次のとおりです(追加のオプションはサポートされていません)。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
export default config;
forceCoverageMatch
[配列<文字列>]
デフォルト: ['']
テストファイルは通常、コードカバレッジの収集から除外されます。このオプションを使用すると、この動作を上書きし、コードカバレッジに無視されたファイルを含めることができます。
たとえば、次のように.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
を設定して、これらのファイルからカバレッジを収集できます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
forceCoverageMatch: ['**/*.t.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
forceCoverageMatch: ['**/*.t.js'],
};
export default config;
globals
[オブジェクト]
デフォルト: {}
すべてのテスト環境で使用可能にする必要があるグローバル変数のセットです。
たとえば、次の操作により、すべてのテスト環境でtrue
に設定されたグローバル__DEV__
変数が作成されます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
globals: {
__DEV__: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
globals: {
__DEV__: true,
},
};
export default config;
ここでグローバル参照値(オブジェクトや配列など)を指定し、テストの実行中にコードがその値を変更した場合、その変更は他のテストファイルのテスト実行間で保持されません。さらに、globals
オブジェクトはJSONでシリアライズ可能である必要があるため、グローバル関数の指定には使用できません。そのためには、setupFiles
を使用する必要があります。
globalSetup
[文字列]
デフォルト: `undefined`
このオプションでは、カスタムグローバル設定モジュールを使用できます。このモジュールは、関数(同期または非同期)をエクスポートする必要があります。この関数は、すべてのテストスイートの前に一度トリガーされ、JestのglobalConfig
とprojectConfig
の2つの引数を受け取ります。
プロジェクト(マルチプロジェクトランナーを使用)で構成されたグローバル設定モジュールは、そのプロジェクトから少なくとも1つのテストを実行した場合にのみトリガーされます。
globalSetup
で定義されたグローバル変数は、globalTeardown
でのみ読み取ることができます。テストスイートでは、ここで定義されたグローバル変数を取得できません。
コード変換はリンクされた設定ファイルに適用されますが、Jestはnode_modules
内のコードを**変換しません**。これは、変換を実行するために実際のトランスフォーマー(例:babel
またはtypescript
)をロードする必要があるためです。
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
// Set reference to mongod in order to close the server during teardown.
globalThis.__MONGOD__ = mongod;
};
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
await globalThis.__MONGOD__.stop();
};
globalTeardown
[文字列]
デフォルト: `undefined`
このオプションでは、関数(同期または非同期)をエクスポートする必要があるカスタムグローバルティアダウンモジュールを使用できます。この関数は、すべてのテストスイートの後に一度トリガーされ、JestのglobalConfig
とprojectConfig
の2つの引数を受け取ります。
プロジェクト(マルチプロジェクトランナーを使用)で構成されたグローバルティアダウンモジュールは、そのプロジェクトから少なくとも1つのテストを実行した場合にのみトリガーされます。
globalSetup
と同様に、node_modules
の変換に関する同じ注意点がglobalTeardown
にも適用されます。
haste
[オブジェクト]
デフォルト: `undefined`
これは、Jestの内部ファイルクロール/キャッシュシステムであるjest-haste-map
の動作を構成するために使用されます。次のオプションがサポートされています。
type HasteConfig = {
/** Whether to hash files using SHA-1. */
computeSha1?: boolean;
/** The platform to use as the default, e.g. 'ios'. */
defaultPlatform?: string | null;
/** Force use of Node's `fs` APIs rather than shelling out to `find` */
forceNodeFilesystemAPI?: boolean;
/**
* Whether to follow symlinks when crawling for files.
* This options cannot be used in projects which use watchman.
* Projects with `watchman` set to true will error if this option is set to true.
*/
enableSymlinks?: boolean;
/** Path to a custom implementation of Haste. */
hasteImplModulePath?: string;
/** All platforms to target, e.g ['ios', 'android']. */
platforms?: Array<string>;
/** Whether to throw on error on module collision. */
throwOnModuleCollision?: boolean;
/** Custom HasteMap module */
hasteMapModulePath?: string;
/** Whether to retain all files, allowing e.g. search for tests in `node_modules`. */
retainAllFiles?: boolean;
};
injectGlobals
[ブール値]
デフォルト: true
Jestのグローバル(expect
、test
、describe
、beforeEach
など)をグローバル環境に挿入します。これをfalse
に設定する場合は、@jest/globals
からインポートする必要があります。例:
import {expect, jest, test} from '@jest/globals';
jest.useFakeTimers();
test('some test', () => {
expect(Date.now()).toBe(0);
});
このオプションは、デフォルトのjest-circus
テストランナーでのみサポートされています。
maxConcurrency
[数値]
デフォルト: 5
test.concurrent
を使用する場合に、同時に実行できるテストの数を制限する数値です。この制限を超えるテストはキューに入れられ、スロットが解放されると実行されます。
maxWorkers
[数値 | 文字列]
ワーカープールがテスト実行のために生成するワーカーの最大数を指定します。単一実行モードでは、これはマシンで使用可能なコア数からメインスレッド用の一つを引いた数にデフォルト設定されます。ウォッチモードでは、Jestが邪魔にならず、マシンを停止させないように、使用可能なコア数の半分にデフォルト設定されます。CIなど、リソースが限られた環境では調整する必要があるかもしれませんが、ほとんどのユースケースではデフォルトで十分です。
使用可能なCPUが可変である環境では、パーセンテージベースの設定を使用できます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
maxWorkers: '50%',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
maxWorkers: '50%',
};
export default config;
moduleDirectories
[array<string>]
デフォルト: ["node_modules"]
要求元のモジュール位置から再帰的に検索されるディレクトリ名の配列です。このオプションを設定すると、デフォルト設定が上書きされます。パッケージに対してnode_modules
を検索する場合も、他のオプションと共に含めてください。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
export default config;
moduleFileExtensions
[array<string>]
デフォルト: ["js", "mjs", "cjs", "jsx", "ts", "tsx", "json", "node"]
モジュールが使用するファイル拡張子の配列です。ファイル拡張子を指定せずにモジュールを要求する場合、Jestは左から右の順にこれらの拡張子を検索します。
プロジェクトで最も一般的に使用される拡張子を左側に配置することをお勧めします。TypeScriptを使用している場合は、「ts」や「tsx」を配列の先頭に移動することを検討してください。
moduleNameMapper
[object<string, string | array<string>>]
デフォルト: null
正規表現からモジュール名、または画像やスタイルなどのリソースを単一のモジュールでスタブ化できるモジュール名の配列へのマップです。
エイリアスにマップされたモジュールは、自動モックが有効になっているかどうかに関係なく、デフォルトではモックされません。
ファイルパスを使用する場合は、rootDir
値を参照するために<rootDir>
文字列トークンを使用してください。
さらに、番号付きの逆参照を使用してキャプチャされた正規表現グループを置き換えることができます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
export default config;
マッピングを定義する順序は重要です。パターンは、適合するパターンが見つかるまで、1つずつチェックされます。最も具体的なルールを最初にリストする必要があります。これは、モジュール名の配列にも当てはまります。
境界^$
なしでモジュール名を提供すると、見つけにくいエラーが発生する可能性があります。例:relay
は、その名前にrelay
を部分文字列として含むすべてのモジュール(relay
、react-relay
、graphql-relay
など)をスタブに置き換えます。
modulePathIgnorePatterns
[array<string>]
デフォルト: []
モジュールローダーに対して「表示可能」と見なされる前に、すべてのモジュールパスに対して照合される正規表現パターン文字列の配列です。特定のモジュールのパスがこれらのパターンのいずれかに一致する場合、テスト環境ではrequire()
できません。
これらのパターン文字列は、完全パスに対して照合されます。プロジェクトのルートディレクトリへのパスを含めるには<rootDir>
文字列トークンを使用してください。これにより、ルートディレクトリが異なる環境で誤ってすべてのファイルを無視してしまうことを防ぎます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
export default config;
modulePaths
[array<string>]
デフォルト: []
NODE_PATH
環境変数を設定するための代替APIとして、modulePaths
は、モジュールを解決するときに検索する追加の場所への絶対パスの配列です。プロジェクトのルートディレクトリへのパスを含めるには<rootDir>
文字列トークンを使用してください。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
modulePaths: ['<rootDir>/app/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePaths: ['<rootDir>/app/'],
};
export default config;
notify
[boolean]
デフォルト: `false`
テスト結果に対してネイティブOS通知を有効にします。通知を表示するには、Jestにnode-notifier
パッケージが必要です。これは別途インストールする必要があります。
- npm
- Yarn
- pnpm
npm install --save-dev node-notifier
yarn add --dev node-notifier
pnpm add --save-dev node-notifier
macOSでは、システム環境設定>通知とフォーカスでterminal-notifier
からの通知を許可することを忘れないでください。
Windowsでは、node-notifier
は最初の使用時に新しいスタートメニューエントリを作成し、通知を表示しません。通知は後続の実行で正しく表示されます。
notifyMode
[string]
デフォルト: failure-change
通知モードを指定します。notify: true
が必要です。
モード
always
: 常に通知を送信します。failure
: テストが失敗したときに通知を送信します。success
: テストが成功したときに通知を送信します。change
: ステータスが変更されたときに通知を送信します。success-change
: テストが成功したとき、または失敗したときに一度通知を送信します。failure-change
: テストが失敗したとき、または成功したときに一度通知を送信します。
openHandlesTimeout
[number]
デフォルト: 1000
Jestが完了してからこのミリ秒数後にクリーンに終了しなかった場合、開いている可能性のあるハンドルを示す警告を出力します。警告を無効にするには0
を使用します。
preset
[string]
デフォルト: `undefined`
Jestの設定のベースとして使用されるプリセットです。プリセットは、ルートにjest-preset.json
、jest-preset.js
、jest-preset.cjs
、またはjest-preset.mjs
ファイルを持つnpmモジュールを指している必要があります。
たとえば、このプリセットfoo-bar/jest-preset.js
は次のように設定されます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
preset: 'foo-bar',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
preset: 'foo-bar',
};
export default config;
プリセットはファイルシステムパスにも関連付けることができます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
preset: './node_modules/foo-bar/jest-preset.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
preset: './node_modules/foo-bar/jest-preset.js',
};
export default config;
rootDir
も指定している場合、このファイルの解決は、そのルートディレクトリを基準に行われます。
prettierPath
[string]
デフォルト: 'prettier'
インラインスナップショットの更新に使用されるprettier
ノードモジュールへのパスを設定します。
Prettierバージョン3はサポートされていません!
必要ない場合は設定でprettierPath: null
を渡してprettierの使用を無効にしたり、Jest専用にPrettierのv2を使用したりできます。
{
"devDependencies": {
"prettier-2": "npm:prettier@^2"
}
}
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
prettierPath: require.resolve('prettier-2'),
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
prettierPath: require.resolve('prettier-2'),
};
export default config;
今後のJestのバージョンで、Prettier v3をシームレスにサポートすることを目指しています。この追跡課題を参照してください。
projects
[array<string | ProjectConfig>]
デフォルト: `undefined`
projects
設定にパスまたはglobパターンの配列が提供されている場合、Jestは指定されたすべてのプロジェクトで同時にテストを実行します。これは、モノレポの場合や、複数のプロジェクトで同時に作業する場合に最適です。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
projects: ['<rootDir>', '<rootDir>/examples/*'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
projects: ['<rootDir>', '<rootDir>/examples/*'],
};
export default config;
この設定例では、ルートディレクトリとexamplesディレクトリのすべてのフォルダでJestを実行します。同じJestインスタンスで実行できるプロジェクトの数に制限はありません。
projects機能は、複数の設定や複数のランナーを実行するためにも使用できます。この目的のために、設定オブジェクトの配列を渡すことができます。たとえば、Jestの同じ呼び出しでテストとESLintの両方(jest-runner-eslint経由)を実行するには
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
projects: [
{
displayName: 'test',
},
{
displayName: 'lint',
runner: 'jest-runner-eslint',
testMatch: ['<rootDir>/**/*.js'],
},
],
};
export default config;
マルチプロジェクトランナーを使用する場合は、各プロジェクトにdisplayName
を追加することをお勧めします。これにより、プロジェクトのdisplayName
がそのテストの横に表示されます。
projects
オプションが有効になっている場合、Jestはテスト実行中にルートレベルの設定オプションを個々の子設定にコピーし、子コンテキストで値を解決します。これは、<rootDir>
などの文字列トークンは、ルートレベルの設定で定義されている場合でも、子のルートディレクトリを指すことを意味します。
randomize
[boolean]
デフォルト: `false`
ファイル内のテストの順序をランダム化する--randomize
フラグと同等です。
reporters
[array<moduleName | [moduleName, options]>]
デフォルト: `undefined`
この設定オプションを使用して、Jestにレポーターを追加します。レポーター名のリストである必要があります。タプル形式を使用して、レポーターに追加のオプションを渡すことができます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [
'default',
['<rootDir>/custom-reporter.js', {banana: 'yes', pineapple: 'no'}],
],
};
export default config;
デフォルトレポーター
カスタムレポーターが指定されている場合、デフォルトのJestレポーターは上書きされます。デフォルトのレポーターを保持する場合は、レポーター名として'default'
を渡す必要があります。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [
'default',
['jest-junit', {outputDirectory: 'reports', outputName: 'report.xml'}],
],
};
export default config;
GitHub Actionsレポーター
リストに含まれている場合、組み込みのGitHub Actionsレポーターは、変更されたファイルにテスト失敗メッセージを注釈付けし('silent: false'
で使用する場合)、簡単なナビゲーションのためにgithubグループ機能を使用してログを出力します。この場合、'github-actions'
が既に処理するため、'default'
を使用しないでください。そのため、'summary'
も必ず含めることを忘れないでください。注釈のみに使用する場合は、'silent'
のデフォルト値は'true'
なので、オプションなしでレポーターのみを残してください。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [['github-actions', {silent: false}], 'summary'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [['github-actions', {silent: false}], 'summary'],
};
export default config;
サマリーレポーター
サマリーレポーターは、すべてのテストのサマリーを出力します。これはデフォルトレポーターの一部であるため、リストに'default'
が含まれている場合に有効になります。たとえば、デフォルトのものに代わるスタンドアロンレポーターとして、またはサイレントレポーターと組み合わせて使用したい場合があります。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: ['jest-silent-reporter', 'summary'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: ['jest-silent-reporter', 'summary'],
};
export default config;
summary
レポーターはオプションを受け入れます。default
レポーターに含まれているため、そこでオプションを渡すこともできます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
reporters: [['default', {summaryThreshold: 10}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
reporters: [['default', {summaryThreshold: 10}]],
};
export default config;
summaryThreshold
オプションは、テストスイートの総数がこのしきい値を超えた場合、すべてのテストを実行した後に、失敗したすべてのテストの詳細なサマリーが出力されます。デフォルトは20
です。
カスタムレポーター
レポーターを探していますか?Awesome Jestの素晴らしいレポーターの長いリストをご覧ください。
カスタムレポーターモジュールは、globalConfig
、reporterOptions
、およびreporterContext
をコンストラクタ引数として受け取るクラスをエクスポートする必要があります。
class CustomReporter {
constructor(globalConfig, reporterOptions, reporterContext) {
this._globalConfig = globalConfig;
this._options = reporterOptions;
this._context = reporterContext;
}
onRunComplete(testContexts, results) {
console.log('Custom reporter output:');
console.log('global config:', this._globalConfig);
console.log('options for this reporter from Jest config:', this._options);
console.log('reporter context passed from test scheduler:', this._context);
}
// Optionally, reporters can force Jest to exit with non zero code by returning
// an `Error` from `getLastError()` method.
getLastError() {
if (this._shouldFail) {
return new Error('Custom error reported!');
}
}
}
module.exports = CustomReporter;
フックと引数の型の完全なリストについては、packages/jest-reporters/src/types.tsのReporter
インターフェースを参照してください。
resetMocks
[boolean]
デフォルト: `false`
各テストの前に、モックの状態を自動的にリセットします。jest.resetAllMocks()
を各テストの前に呼び出すことと同等です。これにより、モックの偽の実装は削除されますが、初期の実装は復元されません。
resetModules
[boolean]
デフォルト: `false`
デフォルトでは、各テストファイルは独自の独立したモジュールレジストリを取得します。resetModules
を有効にすると、さらに一歩進んで、各テストを実行する前にモジュールレジストリをリセットします。これは、各テストのモジュールを分離し、ローカルモジュール状態がテスト間で競合しないようにするために役立ちます。これは、jest.resetModules()
を使用してプログラム的に実行できます。
resolver
[string]
デフォルト: `undefined`
このオプションを使用すると、カスタムレゾルバーを使用できます。このレゾルバーは、どちらかをエクスポートするモジュールである必要があります。
- 解決するパスを最初の引数として受け取る関数と、オプションオブジェクトを2番目の引数として受け取る関数。関数は、解決する必要があるモジュールのパスを返すか、モジュールが見つからない場合はエラーをスローする必要があります。または
async
プロパティと/またはsync
プロパティを含むオブジェクト。sync
プロパティは上記で説明した形状の関数である必要があり、async
プロパティも同様の引数を受け取る関数である必要がありますが、モジュールのパスを解決するPromiseを返し、エラーを拒否します。
レゾルバーに提供されるオプションオブジェクトの形状は次のとおりです。
type ResolverOptions = {
/** Directory to begin resolving from. */
basedir: string;
/** List of export conditions. */
conditions?: Array<string>;
/** Instance of default resolver. */
defaultResolver: (path: string, options: ResolverOptions) => string;
/** List of file extensions to search in order. */
extensions?: Array<string>;
/** List of directory names to be looked up for modules recursively. */
moduleDirectory?: Array<string>;
/** List of `require.paths` to use if nothing is found in `node_modules`. */
paths?: Array<string>;
/** Allows transforming parsed `package.json` contents. */
packageFilter?: (pkg: PackageJSON, file: string, dir: string) => PackageJSON;
/** Allows transforms a path within a package. */
pathFilter?: (pkg: PackageJSON, path: string, relativePath: string) => string;
/** Current root directory. */
rootDir?: string;
};
オプションとして渡されるdefaultResolver
は、Jestのデフォルトレゾルバーです。カスタムレゾルバーを作成する際に役立ちます。これは、カスタムの同期レゾルバーと同じ引数(例:(path, options)
)を受け取り、文字列を返すか、エラーをスローします。
たとえば、Browserifyの"browser"
フィールドを尊重したい場合は、次のレゾルバーを使用できます。
const browserResolve = require('browser-resolve');
module.exports = browserResolve.sync;
そして、それをJestの設定に追加します。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
resolver: '<rootDir>/resolver.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
resolver: '<rootDir>/resolver.js',
};
export default config;
defaultResolver
とpackageFilter
を組み合わせることで、デフォルトレゾルバーがモジュールを解決する方法を変更できるpackage.json
「プリプロセッサ」を実装できます。たとえば、"module"
フィールドが存在する場合はそれを使用し、存在しない場合は"main"
にフォールバックしたいとします。
module.exports = (path, options) => {
// Call the defaultResolver, so we leverage its cache, error handling, etc.
return options.defaultResolver(path, {
...options,
// Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)
packageFilter: pkg => {
return {
...pkg,
// Alter the value of `main` before resolving the package
main: pkg.module || pkg.main,
};
},
});
};
restoreMocks
[boolean]
デフォルト: `false`
各テストの前に、モックの状態と実装を自動的に復元します。jest.restoreAllMocks()
を各テストの前に呼び出すことと同等です。これにより、モックの偽の実装は削除され、初期の実装が復元されます。
rootDir
[string]
デフォルト:Jestの設定ファイル、またはpackage.json
、またはpackage.json
が見つからない場合はpwd
を含むディレクトリのルート。
Jestがテストとモジュールを検索するルートディレクトリ。Jestの設定をpackage.json
内に配置し、ルートディレクトリをリポジトリのルートにしたい場合、この設定パラメータの値はデフォルトでpackage.json
のディレクトリになります。
多くの場合、これはリポジトリ内のコードが格納されている場所に対応して、'src'
または'lib'
に設定します。
他のパスベースの設定で文字列トークンとして'<rootDir>'
を使用すると、この値を参照します。たとえば、プロジェクトのルートにあるsome-setup.js
ファイルを指すsetupFiles
エントリが必要な場合は、その値を'<rootDir>/some-setup.js'
に設定します。
roots
[array<string>]
デフォルト:["<rootDir>"]
Jestがファイルの検索に使用するディレクトリのパスリスト。
リポジトリにsrc/
ディレクトリがある場合など、Jestに単一のサブディレクトリのみを検索させ、リポジトリの残りの部分へのアクセスを防止したい場合があります。
rootDir
は主に他の設定オプションで再利用されるトークンとして使用されますが、roots
はJestの内部で**テストファイルとソースファイル**を見つけるために使用されます。これは、node_modules
からのモジュールのマニュアルモックを検索する場合にも適用されます(__mocks__
はroots
のいずれかに存在する必要があります)。
デフォルトでは、roots
には<rootDir>
という単一のエントリがありますが、1つのプロジェクト内に複数のルートを持つ必要がある場合(例:roots: ["<rootDir>/src/", "<rootDir>/tests/"]
)があります。
runner
[string]
デフォルト:"jest-runner"
このオプションを使用すると、Jestのデフォルトのテストランナーの代わりにカスタムランナーを使用できます。ランナーの例としては、以下があります。
runner
プロパティの値では、パッケージ名のjest-runner-
プレフィックスを省略できます。
テストランナーを作成するには、コンストラクタでglobalConfig
を受け入れるクラスをエクスポートし、次のようなシグネチャを持つrunTests
メソッドを持たせます。
async function runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>;
テストランナーを直列で実行するよう制限する必要がある場合(並列で実行されないように)、クラスのプロパティisSerial
をtrue
に設定する必要があります。
sandboxInjectedGlobals
[array<string>]
Jest 28ではextraGlobals
から名前が変更されました。
デフォルト: `undefined`
テストファイルはvm内で実行され、グローバルコンテキストプロパティ(例:Math
)への呼び出しを遅くします。このオプションを使用すると、より高速なルックアップのために、vm内で定義する追加のプロパティを指定できます。
たとえば、テストでMath
を頻繁に呼び出す場合は、sandboxInjectedGlobals
を設定して渡すことができます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
sandboxInjectedGlobals: ['Math'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
sandboxInjectedGlobals: ['Math'],
};
export default config;
ネイティブESMを使用する場合は、このオプションは効果がありません。
setupFiles
[array]
デフォルト: []
テスト環境の設定またはセットアップを行うコードを実行するモジュールのパスリスト。各setupFileはテストファイルごとに1回実行されます。すべてのテストは独自の環境で実行されるため、これらのスクリプトはsetupFilesAfterEnv
を実行する前、テストコード自体を実行する前に、テスト環境で実行されます。
セットアップスクリプトがCJSモジュールである場合、非同期関数をエクスポートできます。Jestは関数を呼び出し、その結果を待機します。これは、非同期的にいくつかのデータを取得するのに役立つ場合があります。ファイルがESMモジュールである場合は、トップレベルのawaitを使用して同じ結果を得ることができます。
setupFilesAfterEnv
[array]
デフォルト: []
スイート内の各テストファイルが実行される前に、テストフレームワークの設定またはセットアップを行うコードを実行するモジュールのパスリスト。setupFiles
はテストフレームワークが環境にインストールされる前に実行されるため、このスクリプトファイルを使用すると、テストフレームワークが環境にインストールされた直後、テストコード自体が実行される前にコードを実行できます。
言い換えれば、setupFilesAfterEnv
モジュールは、各テストファイルで繰り返されるコードを対象としています。テストフレームワークがインストールされると、Jestのグローバル変数、jest
オブジェクト、およびexpect
がモジュールで使用できるようになります。たとえば、jest-extended
ライブラリから追加のmatcherを追加したり、セットアップとティアダウンフックを呼び出したりできます。
const matchers = require('jest-extended');
expect.extend(matchers);
afterEach(() => {
jest.useRealTimers();
});
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
setupFilesAfterEnv: ['<rootDir>/setup-jest.js'],
};
export default config;
showSeed
[boolean]
デフォルト: `false`
テストレポートのサマリーにシードを出力する--showSeed
フラグと同等です。
slowTestThreshold
[number]
デフォルト: 5
テストが遅いとしてみなされ、結果として報告されるまでの秒数。
snapshotFormat
[object]
デフォルト:{escapeString: false, printBasicPrototype: false}
pretty-formatのREADMEに記載されている特定のスナップショットフォーマットオプションを上書きできます。ただし、compareKeys
とplugins
は例外です。たとえば、この設定では、スナップショットフォーマッタは「Object」と「Array」のプレフィックスを出力しません。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
snapshotFormat: {
printBasicPrototype: false,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
snapshotFormat: {
printBasicPrototype: false,
},
};
export default config;
test('does not show prototypes for object and array inline', () => {
const object = {
array: [{hello: 'Danger'}],
};
expect(object).toMatchInlineSnapshot(`
{
"array": [
{
"hello": "Danger",
},
],
}
`);
});
snapshotResolver
[string]
デフォルト: `undefined`
テスト<->スナップショットパスを解決できるモジュールのパス。この設定オプションを使用すると、Jestがディスクにスナップショットファイルを保存する場所をカスタマイズできます。
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
[array<string>]
デフォルト: []
スナップショットテストで使用されるスナップショットシリアライザモジュールのパスリストです。
Jestは、組み込みのJavaScript型、HTML要素(Jest 20.0.0以降)、ImmutableJS(Jest 20.0.0以降)、React要素に対してデフォルトのシリアライザを持っています。詳細はスナップショットテストチュートリアルを参照してください。
module.exports = {
serialize(val, config, indentation, depth, refs, printer) {
return `Pretty foo: ${printer(val.foo)}`;
},
test(val) {
return val && Object.prototype.hasOwnProperty.call(val, 'foo');
},
};
printer
は、既存のプラグインを使用して値をシリアライズする関数です。
Jestの設定にcustom-serializer
を追加します。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
snapshotSerializers: ['path/to/custom-serializer.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
snapshotSerializers: ['path/to/custom-serializer.js'],
};
export default config;
最終的にテストは以下のようになります。
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
レンダリングされたスナップショット
Pretty foo: Object {
"x": 1,
"y": 2,
}
暗黙的な依存関係ではなく明示的な依存関係にするには、Jestの設定でsnapshotSerializers
にパスを追加する代わりに、個々のテストファイルに対してモジュールを追加するためにexpect.addSnapshotSerializer
を呼び出すことができます。
シリアライザAPIの詳細については、こちらを参照してください。
testEnvironment
[string]
デフォルト: "node"
テストに使用されるテスト環境です。Jestのデフォルトの環境はNode.js環境です。ウェブアプリを構築している場合は、代わりにjsdom
を使用してブラウザのような環境を使用できます。
ファイルの先頭に@jest-environment
ドックブロックを追加することで、そのファイル内のすべてのテストに使用される別の環境を指定できます。
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
テスト環境の設定に使用される独自のモジュールを作成できます。このモジュールは、setup
、teardown
、getVmContext
メソッドを持つクラスをエクスポートする必要があります。また、this.global
オブジェクトに代入することで、このモジュールからテストスイートに変数を渡すことができます。これにより、テストスイートでグローバル変数として使用できるようになります。コンストラクタにはglobalConfig
とprojectConfig
が最初の引数として、testEnvironmentContext
が2番目の引数として渡されます。
このクラスは、jest-circus
によって発生するイベントにバインドするために、非同期handleTestEvent
メソッドをオプションで公開できます。通常、jest-circus
テストランナーは、handleTestEvent
から返されたPromiseが解決されるまで一時停止しますが、**次のイベントを除きます**: start_describe_definition
、finish_describe_definition
、add_hook
、add_test
、error
(最新のリストについては、型定義のSyncEvent型を参照してください)。これは下位互換性の理由とprocess.on('unhandledRejection', callback)
シグネチャによるものですが、ほとんどのユースケースでは通常問題にはなりません。
テストファイル内のすべてのドックブロックプラグマは、環境コンストラクタに渡され、テストごとの設定に使用できます。プラグマに値がない場合は、値が空文字列に設定された状態でオブジェクトに存在します。プラグマが存在しない場合は、オブジェクトにも存在しません。
このクラスをカスタム環境として使用するには、プロジェクト内の完全パスで参照します。たとえば、クラスがプロジェクトのサブフォルダー内のmy-custom-environment.js
に格納されている場合、アノテーションは次のようになります。
/**
* @jest-environment ./src/test/my-custom-environment
*/
TestEnvironmentはサンドボックス化されています。各テストスイートは、独自のTestEnvironmentでsetup/teardownをトリガーします。
例
// my-custom-environment
const NodeEnvironment = require('jest-environment-node').TestEnvironment;
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
console.log(config.globalConfig);
console.log(config.projectConfig);
this.testPath = context.testPath;
this.docblockPragmas = context.docblockPragmas;
}
async setup() {
await super.setup();
await someSetupTasks(this.testPath);
this.global.someGlobalObject = createGlobalObject();
// Will trigger if docblock contains @my-custom-pragma my-pragma-value
if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
// ...
}
}
async teardown() {
this.global.someGlobalObject = destroyGlobalObject();
await someTeardownTasks();
await super.teardown();
}
getVmContext() {
return super.getVmContext();
}
async handleTestEvent(event, state) {
if (event.name === 'test_start') {
// ...
}
}
}
module.exports = CustomEnvironment;
// my-test-suite
/**
* @jest-environment ./my-custom-environment
*/
let someGlobalObject;
beforeAll(() => {
someGlobalObject = globalThis.someGlobalObject;
});
testEnvironmentOptions
[Object]
デフォルト: {}
testEnvironment
に渡されるテスト環境オプションです。関連するオプションは環境によって異なります。
たとえば、jsdom
に渡されるオプションをオーバーライドできます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jest.dokyumento.jp/',
userAgent: 'Agent/007',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jest.dokyumento.jp/',
userAgent: 'Agent/007',
},
};
export default config;
jest-environment-jsdom
とjest-environment-node
の両方でcustomExportConditions
を指定できます。これにより、package.json
のexports
から読み込まれるライブラリのバージョンを制御できます。jest-environment-jsdom
のデフォルトは['browser']
です。jest-environment-node
のデフォルトは['node', 'node-addons']
です。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['react-native'],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['react-native'],
},
};
export default config;
これらのオプションは、testEnvironment
と同様に、ドックブロックでも渡すことができます。オプションを含む文字列は、JSON.parse
で解析可能である必要があります。
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://jest.dokyumento.jp/"}
*/
test('use jsdom and set the URL in this test file', () => {
expect(window.location.href).toBe('https://jest.dokyumento.jp/');
});
testFailureExitCode
[number]
デフォルト: 1
テスト失敗時にJestが返す終了コードです。
これは、Jestエラー(例:無効な設定)の場合の終了コードは変更しません。
testMatch
[array<string>]
(デフォルト: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
)
Jestがテストファイルの検出に使用しているglobパターンです。デフォルトでは、__tests__
フォルダー内の.js
、.jsx
、.ts
、.tsx
ファイル、および.test
または.spec
のサフィックスを持つファイル(例:Component.test.js
またはComponent.spec.js
)を探します。また、test.js
またはspec.js
という名前のファイルも検出します。
指定できるパターンの詳細については、micromatchパッケージを参照してください。
testRegex
[string | array<string>]も参照してください。ただし、両方のオプションを指定することはできません。
各globパターンは、設定で指定されている順序で適用されます。たとえば、["!**/__fixtures__/**", "**/__tests__/**/*.js"]
は、否定が2番目のパターンで上書きされるため、__fixtures__
を除外しません。この例で否定されたglobを機能させるには、**/__tests__/**/*.js
の後に配置する必要があります。
testPathIgnorePatterns
[array<string>]
デフォルト: `["/node_modules/"]`
テストを実行する前に、すべてのテストパスに対して照合される正規表現パターンの配列です。テストパスがパターンのいずれかに一致する場合、スキップされます。
これらのパターン文字列は、完全パスに照合されます。プロジェクトのルートディレクトリへのパスを含めるには、<rootDir>
文字列トークンを使用してください。これにより、ルートディレクトリが異なる環境で誤ってすべてのファイルが無視されるのを防ぐことができます。例: ["<rootDir>/build/", "<rootDir>/node_modules/"]
。
testRegex
[string | array<string>]
デフォルト: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
Jestがテストファイルの検出に使用しているパターンです。デフォルトでは、__tests__
フォルダー内の.js
、.jsx
、.ts
、.tsx
ファイル、および.test
または.spec
のサフィックスを持つファイル(例:Component.test.js
またはComponent.spec.js
)を探します。また、test.js
またはspec.js
という名前のファイルも検出します。testMatch
[array<string>]も参照してください。ただし、両方のオプションを指定することはできません。
デフォルトの正規表現の可視化です。
├── __tests__
│ └── component.spec.js # test
│ └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test
testRegex
は**絶対ファイルパス**を使用してテストファイルの検出を試みるため、それに一致する名前のフォルダーがあると、すべてのファイルがテストとして実行されます。
testResultsProcessor
[string]
デフォルト: `undefined`
このオプションでは、カスタムの結果プロセッサを使用できます。このプロセッサは、次の構造を持つオブジェクトを最初の引数として受け取り、それを返す関数をエクスポートするノードモジュールである必要があります。
{
"success": boolean,
"startTime": epoch,
"numTotalTestSuites": number,
"numPassedTestSuites": number,
"numFailedTestSuites": number,
"numRuntimeErrorTestSuites": number,
"numTotalTests": number,
"numPassedTests": number,
"numFailedTests": number,
"numPendingTests": number,
"numTodoTests": 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
},
"duration": number | null
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": absolute path to test file,
"coverage": {}
},
"testExecError:" (exists if there was a top-level failure) {
"message": string
"stack": string
}
...
]
}
testResultsProcessor
とreporters
は非常に似ていますが、テスト結果プロセッサはすべてのテストが終了した後にのみ呼び出されるという違いがあります。一方、レポーターは、個々のテストやテストスイートが終了した後にテスト結果を受け取る機能があります。
testRunner
[string]
デフォルト: jest-circus/runner
このオプションでは、カスタムのテストランナーを使用できます。デフォルトはjest-circus
です。カスタムテストランナーは、テストランナー実装へのパスを指定することで提供できます。
テストランナーモジュールは、次のシグネチャを持つ関数をエクスポートする必要があります。
function testRunner(
globalConfig: GlobalConfig,
config: ProjectConfig,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
そのような関数の例は、デフォルトのjasmine2テストランナーパッケージにあります。
testSequencer
[string]
デフォルト: @jest/test-sequencer
このオプションを使用すると、Jestのデフォルトの代わりにカスタムシーケンサを使用できます。
sort
とshard
は、オプションでPromise
を返すことができます。
たとえば、テストパスをアルファベット順にソートできます。
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
/**
* Select tests for shard requested via --shard=shardIndex/shardCount
* Sharding is applied before sorting
*/
shard(tests, {shardIndex, shardCount}) {
const shardSize = Math.ceil(tests.length / shardCount);
const shardStart = shardSize * (shardIndex - 1);
const shardEnd = shardSize * shardIndex;
return [...tests]
.sort((a, b) => (a.path > b.path ? 1 : -1))
.slice(shardStart, shardEnd);
}
/**
* Sort test to determine order of execution
* Sorting is applied after sharding
*/
sort(tests) {
// Test structure information
// https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
const copyTests = [...tests];
return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
}
}
module.exports = CustomSequencer;
Jestの設定にcustom-sequencer
を追加します。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testSequencer: 'path/to/custom-sequencer.js',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
testSequencer: 'path/to/custom-sequencer.js',
};
export default config;
testTimeout
[number]
デフォルト: 5000
テストのデフォルトのタイムアウト(ミリ秒単位)。
transform
[object<string, pathToTransformer | [pathToTransformer, object]>]
デフォルト: {"\\.[jt]sx?$": "babel-jest"}
正規表現からトランスフォーマへのパスのマップです。オプションで、構成オプションのタプルを2番目の引数として渡すことができます: {filePattern: ['path-to-transformer', {options}]}
。たとえば、デフォルト以外の動作についてbabel-jest
を構成する方法は次のとおりです: {'\\.js$': ['babel-jest', {rootMode: 'upward'}]}
。
JestはプロジェクトのコードをJavaScriptとして実行するため、Node.jsで標準的にサポートされていない構文(JSX、TypeScript、Vueテンプレートなど)を使用する場合は、トランスフォーマーが必要です。デフォルトでは、Jestはbabel-jest
トランスフォーマーを使用します。これは、プロジェクトのBabel設定を読み込み、/\.[jt]sx?$/
正規表現に一致する任意のファイル(つまり、任意の.js
、.jsx
、.ts
、.tsx
ファイル)を変換します。ESモジュールのモックで説明されているモックホーティングに必要なBabelプラグインもbabel-jest
によって注入されます。
詳細と独自のトランスフォーマーの作成方法については、「コード変換」セクションを参照してください。
ファイルが変更されない限り、トランスフォーマーはファイルごとに1回だけ実行されることに注意してください。
追加のコードプリプロセッサと併せて使用する場合は、デフォルトのbabel-jest
トランスフォーマーを明示的に含めるようにしてください。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.css$': 'some-css-transformer',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.css$': 'some-css-transformer',
},
};
export default config;
transformIgnorePatterns
[array<string>]
デフォルト: ["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
変換前にすべてのソースファイルパスに対して照合される正規表現パターン文字列の配列です。ファイルパスがこれらのパターンのいずれかに一致する場合は、変換されません。
互いに重複する正規表現パターンを指定すると、変換されることが期待されるファイルが変換されない可能性があります。例:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'],
};
export default config;
最初のパターンは/node_modules
内のファイルを一致させ(したがって変換しません)、/node_modules/foo/
と/node_modules/bar/
内のファイルは除きます。2番目のパターンは、パス内に/bar/
が含まれるすべてのファイルと一致します(したがって変換しません)。これらを組み合わせると、/node_modules/bar/
内のファイルは2番目のパターンと一致するため、たとえ最初のによって除外されていたとしても、変換されません。
サードパーティモジュールがトランスパイルされていないコードとして公開されている場合(特にReact NativeまたはTypeScriptプロジェクトで)があります。デフォルトではnode_modules
内のすべてのファイルは変換されないため、Jestはこれらのモジュール内のコードを理解できず、構文エラーが発生します。これを解決するには、transformIgnorePatterns
を使用して、そのようなモジュールのトランスパイルを許可できます。このユースケースの良い例は、「React Nativeガイド」にあります。
これらのパターン文字列は、完全パスに対して照合されます。プロジェクトのルートディレクトリへのパスを含めるには<rootDir>
文字列トークンを使用してください。これにより、ルートディレクトリが異なる環境で誤ってすべてのファイルを無視してしまうことを防ぎます。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: [
'<rootDir>/bower_components/',
'<rootDir>/node_modules/',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: [
'<rootDir>/bower_components/',
'<rootDir>/node_modules/',
],
};
export default config;
pnpm
を使用していて、node_modules
の下にある一部のパッケージを変換する必要がある場合は、このフォルダ(例:node_modules/package-a/
)のパッケージが.pnpm
(例:node_modules/.pnpm/package-a@x.x.x/node_modules/package-a/
)の下のパスにシンボリックリンクされていることに注意する必要があります。そのため、<rootDir>/node_modules/(?!(package-a|@scope/pkg-b)/)
を直接使用しても認識されません。代わりに使用する必要があります。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
transformIgnorePatterns: [
'<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
/* if config file is under '~/packages/lib-a/' */
`${path.join(
__dirname,
'../..',
)}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
/* or using relative pattern to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@x.x.x/node_modules/@scope/pkg-b/' */
'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
transformIgnorePatterns: [
'<rootDir>/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)',
/* if config file is under '~/packages/lib-a/' */
`${path.join(
__dirname,
'../..',
)}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`,
/* or using relative path to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@x.x.x/node_modules/@scope/pkg-b/' */
'node_modules/(?!.pnpm|package-a|@scope/pkg-b)',
],
};
export default config;
.pnpm
の下のpnpmのフォルダ名は、パッケージ名に「@」とバージョン番号が付加されたものであるため、「/」を使用しても認識されませんが、「@」を使用すると認識されます。
unmockedModulePathPatterns
[array<string>]
デフォルト: []
モジュールローダーが自動的にモックを返す前に、すべてのモジュールに対して照合される正規表現パターン文字列の配列です。モジュールのパスがこのリストのパターンのいずれかに一致する場合は、モジュールローダーによって自動的にモックされません。
これは、ほとんどの場合実装の詳細として使用される一般的な「ユーティリティ」モジュール(underscore
、lodash
など)に役立ちます。このリストをできるだけ小さくし、個々のテストで明示的なjest.mock()
/jest.unmock()
呼び出しを常に使用する方が一般的によい習慣です。テストの他の読者にとって、テストが実行される環境を理解することは、明示的なテストごとの設定の方がはるかに容易です。
テストファイルの先頭にjest.mock()
を明示的に呼び出すことで、個々のテストでこの設定を上書きできます。
verbose
[boolean]
デフォルト: false
、または実行するテストファイルが1つしかない場合はtrue
実行中に個々のテストを報告するかどうかを示します。すべてのエラーも実行後、下部に表示されます。
watchPathIgnorePatterns
[array<string>]
デフォルト: []
ウォッチモードでテストを再実行する前に、すべてのソースファイルパスに対して照合されるRegExpパターンの配列です。ファイルパスがこれらのパターンのいずれかに一致する場合は、更新されてもテストの再実行はトリガーされません。
これらのパターンは完全なパスに一致します。異なるルートディレクトリを持つ可能性のあるさまざまな環境で、誤ってすべてのファイルを無視しないように、プロジェクトのルートディレクトリへのパスを含めるには、<rootDir>
文字列トークンを使用します。例: ["<rootDir>/node_modules/"]
。
ここに何も指定されていない場合でも、ウォッチャーはバージョン管理フォルダ(.git、.hg、.sl)への変更を無視します。その他の隠しファイルとディレクトリ(つまり、ドット(.
)で始まるもの)は、デフォルトで監視されます。特殊なRegExp文字であるため、watchPathIgnorePatterns
に追加する際には、ドットをエスケープすることを忘れないでください。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
watchPathIgnorePatterns: ['<rootDir>/\\.tmp/', '<rootDir>/bar/'],
};
export default config;
watchPlugins
[array<string | [string, Object]>]
デフォルト: []
このオプションを使用すると、カスタムウォッチプラグインを使用できます。ウォッチプラグインの詳細については、こちらを参照してください。
ウォッチプラグインの例を以下に示します。
jest-watch-master
jest-watch-select-projects
jest-watch-suspend
jest-watch-typeahead
jest-watch-yarn-workspaces
watchPlugins
プロパティ値の値では、パッケージ名のjest-watch-
プレフィックスを省略できます。
watchman
[boolean]
デフォルト: true
ファイルクロールにwatchman
を使用するかどうか。
workerIdleMemoryLimit
[number|string]
デフォルト: `undefined`
この問題に対する回避策として主に使用され、ワーカーがリサイクルされる前のメモリ制限を指定します。
ワーカーがテストを実行した後、そのメモリ使用量がチェックされます。指定された値を超えると、ワーカーはキルされ、再起動されます。制限はさまざまな方法で指定でき、結果はMath.floor
を使用して整数値に変換されます。
<= 1
- 値はシステムメモリの割合とみなされます。したがって、0.5はワーカーのメモリ制限をシステムメモリの半分に設定します。\> 1
- 固定バイト値とみなされます。前のルールのため、1バイトの値(理由はわかりませんが)が必要な場合は1.1
を使用できます。- 単位付き
50%
- 上記のように、システムメモリの割合。100KB
、65MB
など - 固定メモリ制限を示す単位付き。K
/KB
- キロバイト (x1000)KiB
- キビバイト (x1024)M
/MB
- メガバイトMiB
- メビバイトG
/GB
- ギガバイトGiB
- ギビバイト
割合ベースのメモリ制限は、Linux CircleCIワーカーでは、システムメモリの報告が正しくないため機能しません。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
workerIdleMemoryLimit: 0.2,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
workerIdleMemoryLimit: 0.2,
};
export default config;
//
[string]
このオプションを使用すると、package.json
にコメントを含めることができます。このキーの値としてコメントテキストを含めます。
{
"name": "my-project",
"jest": {
"//": "Comment goes here",
"verbose": true
}
}
workerThreads
デフォルト: `false`
並列化にワーカー スレッドを使用するかどうか。デフォルトでは子プロセスが使用されます。
ワーカー スレッドを使用すると、パフォーマンスが向上する可能性があります。
これは実験的な機能です。ワーカー スレッドは、メッセージのシリアル化にJSON.stringify()
ではなく構造化クローンを使用することに注意してください。つまり、BigInt
、Map
、Set
などの組み込みJavaScriptオブジェクトは適切にシリアル化されます。ただし、Error
、Map
、Set
に設定された追加のプロパティは、シリアル化ステップでは渡されません。詳細については、「構造化クローン」に関する記事を参照してください。