設定 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 組態檔,Jest 需要 ts-node
。請確認已安裝在您的專案中。
組態也可以儲存在 JSON 檔中,作為一個純粹的物件
{
"bail": 1,
"verbose": true
}
或者,也可以透過專案的 package.json
中的 "jest"
鍵來定義 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
[布林值]bail
[數字 | 布林值]cacheDirectory
[字串]clearMocks
[布林值]collectCoverage
[布林值]collectCoverageFrom
[陣列]coverageDirectory
[字串]coveragePathIgnorePatterns
[陣列<字串>]coverageProvider
[字串]coverageReporters
[陣列<字串 | [字串,選項]>]coverageThreshold
[物件]dependencyExtractor
[字串]displayName
[字串,物件]errorOnDeprecated
[布林值]extensionsToTreatAsEsm
[陣列<字串>]fakeTimers
[物件]forceCoverageMatch
[陣列<字串>]globals
[物件]globalSetup
[字串]globalTeardown
[字串]haste
[物件]injectGlobals
[布林值]maxConcurrency
[數字]maxWorkers
[數字 | 字串]moduleDirectories
[陣列<字串>]moduleFileExtensions
[陣列<字串>]moduleNameMapper
[物件<字串,字串 | 陣列<字串>>]modulePathIgnorePatterns
[陣列<字串>]modulePaths
[陣列<字串>]notify
[布林值]notifyMode
[字串]openHandlesTimeout
[數字]preset
[字串]prettierPath
[字串]projects
[陣列<字串 | 專案組態>]randomize
[布林值]reporters
[陣列<模組名稱 | [模組名稱,選項]>]resetMocks
[布林值]resetModules
[布林值]resolver
[字串]restoreMocks
[布林值]rootDir
[字串]roots
[陣列<字串>]runner
[字串]sandboxInjectedGlobals
[陣列<字串>]setupFiles
[陣列]setupFilesAfterEnv
[陣列]showSeed
[布林值]slowTestThreshold
[數字]snapshotFormat
[物件]snapshotResolver
[字串]snapshotSerializers
[陣列<字串>]testEnvironment
[字串]testEnvironmentOptions
[物件]testFailureExitCode
[數字]testMatch
[陣列<字串>]testPathIgnorePatterns
[陣列<字串>]testRegex
[字串 | 陣列<字串>]testResultsProcessor
[字串]testRunner
[字串]testSequencer
[字串]testTimeout
[數字]transform
[物件<字串, 路徑到轉換器 | [路徑到轉換器, 物件]>]transformIgnorePatterns
[陣列<字串>]unmockedModulePathPatterns
[陣列<字串>]verbose
[布林值]watchPathIgnorePatterns
[陣列<字串>]watchPlugins
[陣列<字串 | [字串, 物件]>]watchman
[布林值]workerIdleMemoryLimit
[數字 | 字串]//
[字串]workerThreads
參考
automock
[布林值]
預設值: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();
});
當您有手動模擬時,Node 模組會自動模擬(例如:__mocks__/lodash.js
)。更多資訊 在此。
預設情況下,不會模擬 Node.js 核心模組,例如 fs
。它們可以明確模擬,例如 jest.mock('fs')
。
bail
[數字 | 布林值]
預設值:0
預設情況下,Jest 會執行所有測試,並在完成後將所有錯誤產生到主控台。可以在這裡使用 bail 設定選項,讓 Jest 在 n
次失敗後停止執行測試。將 bail 設為 true
等於將 bail 設為 1
。
cacheDirectory
[字串]
預設值:"/tmp/<path>"
Jest 應該儲存其快取相依性資訊的目錄。
Jest 會嘗試掃描您的相依性樹一次(預先),並將其快取,以減輕執行測試時需要進行的一些檔案系統變更。此設定選項讓您可以自訂 Jest 在磁碟上儲存快取資料的位置。
clearMocks
[布林值]
預設值:false
在每個測試之前自動清除模擬呼叫、執行個體、內容和結果。等同於在每個測試之前呼叫 jest.clearAllMocks()
。這不會移除可能已提供的任何模擬實作。
collectCoverage
[布林值]
預設值:false
指出是否應在執行測試時收集涵蓋範圍資訊。由於這會為所有執行的檔案加上涵蓋範圍收集陳述式,因此可能會大幅降低測試速度。
Jest 附帶兩個涵蓋範圍提供者:babel
(預設值)和 v8
。請參閱 coverageProvider
選項以取得更多詳細資料。
babel
和 v8
涵蓋範圍提供者分別使用 /* istanbul ignore next */
和 /* c8 ignore next */
註解來從涵蓋範圍報告中排除行。如需更多資訊,您可以查看 istanbuljs
文件 和 c8
文件。
collectCoverageFrom
[陣列]
預設值: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;
這將收集專案的 rootDir
內所有檔案的涵蓋範圍資訊,但會排除符合 **/node_modules/**
或 **/vendor/**
的檔案。
每個 glob 模式會按照在設定中指定的順序套用。例如,["!**/__tests__/**", "**/*.js"]
這個設定不會排除 __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 模式很可能沒有符合任何檔案。請參閱 micromatch 文件,以確保您的 glob 相容。
coverageDirectory
[字串]
預設值:undefined
Jest 應該輸出涵蓋範圍檔案的目錄。
coveragePathIgnorePatterns
[字串陣列]
預設值:["/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;
如果在 global
旁邊指定 glob 或路徑,與路徑相符的涵蓋率資料將從整體涵蓋率中減去,並且臨界值將獨立套用。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;
如果
./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
函數應傳回一個可迭代的(陣列
、集合
等)物件,其中包含程式碼中找到的相依性。
該模組也可以包含一個 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
的預設值為白色,當其值為字串時。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 會將 .mjs
和 .js
檔案與最近的 package.json
的 type
欄位設定為 module
作為 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()
將使用這些選項,或者如果傳遞設定物件,它將覆寫這些選項。例如,您可以告訴 Jest 保留 process.nextTick()
的原始實作,並調整將執行的遞迴計時器的限制
- 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
[array<string>]
預設值:['']
測試檔案通常會從收集程式碼覆蓋率中忽略。使用此選項,您可以覆寫此行為,並將原本忽略的檔案包含在程式碼覆蓋率中。
例如,如果您在命名為 .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
[object]
預設值:{}
一組需要在所有測試環境中可用的全域變數。
例如,下列會在所有測試環境中建立一個全域變數 __DEV__
,並設定為 true
- 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
[string]
預設值:undefined
此選項允許使用自訂全域設定模組,該模組必須匯出一個函式(可以是同步或非同步)。此函式將在所有測試套件之前觸發一次,且會收到兩個參數:Jest 的 globalConfig
和 projectConfig
。
在專案中設定的全域設定模組(使用多專案執行器)將只會在您至少執行此專案中的其中一個測試時觸發。
透過 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
此選項允許使用自訂的全局 teardown 模組,此模組必須匯出一個函式(可以是同步或非同步)。此函式會在所有測試套件之後觸發一次,並會收到兩個引數:Jest 的 globalConfig
和 projectConfig
。
在專案中設定的全局 teardown 模組(使用多專案執行器)將只會在您從此專案執行至少一個測試時觸發。
globalSetup
的 node_modules
轉換警告也適用於 globalTeardown
。
haste
[物件]
預設值:undefined
這將用於設定 jest-haste-map
的行為,Jest 的內部檔案爬蟲/快取系統。支援下列選項
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
[陣列<字串>]
預設值:["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
[陣列<字串>]
預設值:["js", "mjs", "cjs", "jsx", "ts", "tsx", "json", "node"]
一個你的模組使用的檔案副檔名陣列。如果你需要模組而沒有指定檔案副檔名,這些是 Jest 會尋找的副檔名,由左至右順序。
我們建議將專案中最常使用的副檔名放在左側,因此如果你正在使用 TypeScript,你可能想要考慮將 "ts" 和/或 "tsx" 移到陣列的開頭。
moduleNameMapper
[物件<字串, 字串 | 陣列<字串>>]
預設值: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;
定義對應的順序很重要。模式會逐一檢查,直到找到一個符合的模式。最具體的規則應該先列出。對於模組名稱陣列也是如此。
如果你提供沒有邊界的模組名稱 ^$
,可能會導致難以發現的錯誤。例如:relay
將取代所有模組名稱中包含 relay
作為子字串的模組:relay
、react-relay
和 graphql-relay
都會指向你的存根。
modulePathIgnorePatterns
[陣列<字串>]
預設值:[]
在模組載入器將所有模組路徑視為「可見」之前,與這些路徑比對的一系列 regexp 模式字串。如果給定的模組路徑與任何模式相符,它將無法在測試環境中 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
[陣列<字串>]
預設值:[]
設定 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
[布林值]
預設值:false
啟用測試結果的原生作業系統通知。若要顯示通知,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
[字串]
預設值:failure-change
指定通知模式。需要 notify: true
。
模式
always
:總是傳送通知。failure
:在測試失敗時傳送通知。success
:在測試通過時傳送通知。change
:在狀態變更時傳送通知。success-change
:在測試通過時或失敗時一次性發送通知。failure-change
:在測試失敗時或通過時一次性發送通知。
openHandlesTimeout
[數字]
預設:1000
列印警告,指出在 Jest 在完成後此毫秒數內未正常結束,則可能有開啟的句柄。使用 0
來停用警告。
preset
[字串]
預設值:undefined
用作 Jest 組態基礎的預設。預設應指向 npm 模組,其中在根目錄有 jest-preset.json
、jest-preset.js
、jest-preset.cjs
或 jest-preset.mjs
檔案。
例如,此預設 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
[字串]
預設:'prettier'
設定路徑至 prettier
node 模組,用於更新內嵌快照。
不支援 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
[陣列<字串 | 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 執行個體中執行無限量的專案。
專案功能也可用于執行多個組態或多個 執行器。為此,您可以傳遞組態物件陣列。例如,在同一個 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
[布林值]
預設值:false
等同於 --randomize
旗標,用於將檔案中測試的順序隨機化。
reporters
[陣列<模組名稱 | [模組名稱,選項]>]
預設值: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 群組功能的日誌,以利於導覽。請注意,在這種情況下不應使用 'default'
,因為 'github-actions'
已處理完畢,因此請記得也包含 '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'
,它將會被啟用。例如,您可能希望將它用作獨立報表員,而不是預設報表員,或與 Silent Reporter 一起使用
- 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
[布林值]
預設值:false
在每個測試前自動重設模擬狀態。等同於在每個測試前呼叫 jest.resetAllMocks()
。這將導致移除所有模擬的偽實作,但不會復原其初始實作。
resetModules
[布林值]
預設值:false
預設情況下,每個測試檔案都會取得其自己的獨立模組註冊表。啟用 resetModules
會更進一步,在執行每個個別測試前重設模組註冊表。這有助於為每個測試隔離模組,讓區域模組狀態不會在測試間衝突。這可以使用 jest.resetModules()
以程式方式執行。
resolver
[字串]
預設值:undefined
此選項允許使用自訂解析器。此解析器必須是一個模組,匯出下列任一項
- 一個函式,將字串作為解析路徑的第一個引數,將選項物件作為第二個引數。此函式應傳回要解析的模組路徑,或在找不到模組時擲回錯誤。或
- 一個包含
async
和/或sync
屬性的物件。sync
屬性應為具有上述形狀的函式,而async
屬性也應為接受相同引數的函式,但傳回一個承諾,其中解析模組路徑或拒絕錯誤。
提供給解析器的選項物件具有以下形狀
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
[布林值]
預設值:false
在每次測試前自動還原模擬狀態和實作。等同於在每次測試前呼叫 jest.restoreAllMocks()
。這會移除所有模擬的偽實作並還原其初始實作。
rootDir
[字串]
預設值:包含 Jest 設定檔 的目錄根目錄或package.json
或pwd
(如果找不到 package.json
)
Jest 應在其中掃描測試和模組的根目錄。如果您將 Jest 設定檔放入 package.json
中,並希望根目錄為儲存庫的根目錄,則此設定參數的值會預設為 package.json
的目錄。
通常,您會希望將此設定為 'src'
或 'lib'
,這會對應於儲存庫中儲存程式碼的位置。
在任何其他基於路徑的設定設定中使用 '<rootDir>'
作為字串權杖會參考回此值。例如,如果您希望 setupFiles
項目指向專案根目錄中的 some-setup.js
檔案,請將其值設定為:'<rootDir>/some-setup.js'
。
roots
[陣列<字串>]
預設值:["<rootDir>"]
Jest 應使用來搜尋檔案的目錄路徑清單。
有些時候,您只希望 Jest 在單一子目錄中搜尋(例如,儲存庫中含有 src/
目錄的情況),但禁止它存取儲存庫的其餘部分。
雖然 rootDir
主要用作重新用於其他組態選項的標記,但 roots
則由 Jest 內部用於尋找測試檔案和原始碼檔案。這也適用於搜尋來自 node_modules
的模組的手動模擬(__mocks__
需要存在於其中一個 roots
中)。
預設情況下,roots
有單一項目 <rootDir>
,但在某些情況下,您可能希望在一個專案中有多個根目錄,例如 roots: ["<rootDir>/src/", "<rootDir>/tests/"]
。
runner
[字串]
預設值:"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
[陣列<字串>]
在 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
[陣列]
預設值:[]
一個模組路徑清單,這些模組執行一些程式碼來組態或設定測試環境。每個 setupFile 會在每個測試檔案中執行一次。由於每個測試都在自己的環境中執行,這些指令碼會在執行 setupFilesAfterEnv
和測試程式碼本身之前,在測試環境中執行。
如果您的設定指令碼是 CJS 模組,它可能會匯出一個非同步函式。Jest 會呼叫這個函式並等待它的結果。這可能有助於非同步擷取一些資料。如果檔案是 ESM 模組,只需使用頂層 await 即可達到相同的結果。
setupFilesAfterEnv
[陣列]
預設值:[]
一個模組路徑清單,這些模組執行一些程式碼來組態或設定測試架構,在套件中的每個測試檔案執行之前執行。由於 setupFiles
在測試架構安裝在環境中之前執行,這個指令碼檔案讓您有機會在測試架構安裝在環境中之後,但在測試程式碼本身之前執行一些程式碼。
換句話說,setupFilesAfterEnv
模組是針對在每個測試檔案中重複出現的程式碼而設計的。安裝測試架構後,Jest 會在模組中提供 全域變數、jest
物件 和 expect
。例如,您可以從 jest-extended
函式庫新增額外的比對器,或呼叫 設定和中斷 鉤子
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
[布林值]
預設值:false
等於 --showSeed
旗標,用於在測試報告摘要中列印種子。
slowTestThreshold
[數字]
預設值:5
測試被視為執行緩慢並在結果中報告為緩慢的秒數。
snapshotFormat
[物件]
預設值:{escapeString: false, printBasicPrototype: false}
允許覆寫 pretty-format readme 中記載的特定快照格式化選項,但例外的是 compareKeys
和 plugins
。例如,這個設定會讓快照格式器不會為「物件」和「陣列」印出前置詞
- 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
[字串]
預設值: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
[陣列<字串>]
預設值:[]
Jest 應該用於快照測試的快照序列化器模組路徑清單。
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
是使用現有外掛程式序列化值的函式。
將 custom-serializer
新增到您的 Jest 設定
- 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,
}
若要讓依賴關係明確而非隱含,您可以呼叫 expect.addSnapshotSerializer
來新增模組給個別測試檔案,而非在 Jest 設定中將其路徑新增至 snapshotSerializers
。
更多關於序列化器 API 的資訊可在此處找到 here。
testEnvironment
[字串]
預設值:"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
作為其第二個引數。
此類別可以選擇公開一個非同步的 handleTestEvent
方法來繫結至 jest-circus
所觸發的事件。通常,jest-circus
測試執行器會暫停,直到從 handleTestEvent
傳回的承諾得到滿足,但以下事件除外: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 中觸發設定/清除。
範例
// 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
[物件]
預設值:{}
將傳遞至 testEnvironment
的測試環境選項。相關選項取決於環境。
例如,你可以覆寫傳遞至 jsdom
的選項
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
html: '<html lang="zh-cmn-Hant"></html>',
url: 'https://jest.dev.org.tw/',
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.dev.org.tw/',
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.dev.org.tw/"}
*/
test('use jsdom and set the URL in this test file', () => {
expect(window.location.href).toBe('https://jest.dev.org.tw/');
});
testFailureExitCode
[數字]
預設:1
測試失敗時 Jest 傳回的退出碼。
這不會在 Jest 錯誤(例如無效設定)的情況下變更退出碼。
testMatch
[陣列<字串>]
(預設:[ "**/__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
[字串 | 陣列<字串>],但請注意您無法同時指定這兩個選項。
每個 glob 模式會按照在設定中指定的順序套用。例如,["!**/__fixtures__/**", "**/__tests__/**/*.js"]
因為否定會被第二個模式覆寫,所以不會排除 __fixtures__
。為了讓否定的 glob 在此範例中運作,它必須出現在 **/__tests__/**/*.js
之後。
testPathIgnorePatterns
[陣列<字串>]
預設值:["/node_modules/"]
在執行測試前,會比對所有測試路徑的 regexp 模式字串陣列。如果測試路徑符合任何模式,它將會被略過。
這些模式字串會與完整路徑進行比對。使用 <rootDir>
字串代碼,可以包含專案根目錄的路徑,以避免在不同的環境中意外忽略所有檔案,因為這些環境可能會有不同的根目錄。範例:["<rootDir>/build/", "<rootDir>/node_modules/"]
。
testRegex
[字串 | 陣列<字串>]
預設值:(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
Jest 使用的模式或模式來偵測測試檔案。預設會在 __tests__
資料夾中尋找 .js
、.jsx
、.ts
和 .tsx
檔案,以及任何字尾為 .test
或 .spec
的檔案(例如 Component.test.js
或 Component.spec.js
)。它也會找到名為 test.js
或 spec.js
的檔案。另請參閱 testMatch
[陣列<字串>],但請注意您無法同時指定這兩個選項。
以下是預設 regex 的視覺化
├── __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
[字串]
預設值: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
[字串]
預設值:jest-circus/runner
此選項允許使用自訂測試執行器。預設值是 jest-circus
。可以透過指定自訂測試執行器實作的路徑來提供自訂測試執行器。
測試執行器模組必須匯出一個函式,且具有下列簽章
function testRunner(
globalConfig: GlobalConfig,
config: ProjectConfig,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
此類函式的範例可以在我們的預設 jasmine2 測試執行器套件 中找到。
testSequencer
[字串]
預設:@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;
將 custom-sequencer
加入您的 Jest 組態
- 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
[數字]
預設:5000
測試的預設逾時時間(毫秒)。
transform
[物件<字串,路徑至轉換器 | [路徑至轉換器,物件]>]
預設:{"\\.[jt]sx?$": "babel-jest"}
從正規表示式到轉換器路徑的對應。選擇性地,可以將包含組態選項的組傳遞為第二個參數:{filePattern: ['path-to-transformer', {options}]}
。例如,以下是您如何為非預設行為組態 babel-jest
的方式:{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}
。
Jest 以 JavaScript 執行專案的程式碼,因此如果您使用某些 Node 本身不支援的語法(例如 JSX、TypeScript、Vue 範本),則需要轉換器。預設情況下,Jest 將使用 babel-jest
轉換器,它將載入專案的 Babel 組態並轉換任何符合 /\.[jt]sx?$/
正規表示式的檔案(換句話說,任何 .js
、.jsx
、.ts
或 .tsx
檔案)。此外,babel-jest
將注入 ES 模組模擬 中所述的模擬提升所需 Babel 外掛程式。
請參閱 程式碼轉換 部分,以取得更多詳細資訊和建立您自己的轉換器的說明。
請記住,除非檔案已變更,否則每個檔案只會執行一次轉換器。
如果您希望與其他程式碼預處理器一起使用,請記得明確包含預設的 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/
內的檔案除外。第二個模式會比對(因此不會轉換)任何路徑中包含 /bar/
的檔案。將這兩個模式結合使用時,/node_modules/bar/
中的檔案不會轉換,因為它符合第二個模式,即使它已被第一個模式排除在外。
有時會發生(特別是在 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
或 true
,如果只有一個測試檔案要執行
表示是否應在執行期間報告每個個別測試。所有錯誤仍會在執行後顯示在底部。
watchPathIgnorePatterns
[array<string>]
預設值:[]
在監控模式下重新執行測試之前,與所有原始檔路徑比對的 RegExp 模式陣列。如果檔案路徑與任何模式相符,在更新時,它不會觸發重新執行測試。
這些模式與完整路徑相符。使用 <rootDir>
字串代碼來包含專案根目錄的路徑,以防止它意外忽略在不同環境中可能具有不同根目錄的所有檔案。範例:["<rootDir>/node_modules/"]
。
即使在此處未指定任何內容,監控器也會忽略版本控制資料夾的變更(.git、.hg、.sl)。預設會監控其他隱藏檔案和目錄,即以句點 (.
) 開頭的檔案和目錄。將它們新增至 watchPathIgnorePatterns
時,請記得跳脫句點,因為它是特殊的 RegExp 字元。
- 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;
//
[字串]
此選項允許在 package.json
中使用註解。將註解文字包含為此金鑰的值
{
"name": "my-project",
"jest": {
"//": "Comment goes here",
"verbose": true
}
}
workerThreads
預設值:false
使用工作執行緒可能有助於提升 效能。
這是實驗性功能。請記住,工作執行緒使用結構化複製,而不是 JSON.stringify()
來序列化訊息。這表示內建的 JavaScript 物件,例如 BigInt
、Map
或 Set
,將會正確序列化。然而,在 Error
、Map
或 Set
上設定的額外屬性將不會透過序列化步驟傳遞。如需更多詳細資訊,請參閱有關 結構化複製 的文章。