翻譯自:https://jestjs.io/docs/zh-Hans/configuration
最新更新:2020/01
Jest的配置可以通過package.json或是jest.config.js文件來配置螃诅,支持多種文件后綴亡脸,格式
如下:
--config <path/to/file.js|cjs|mjs|json>
想要在package.json中配置的可以引入jest字段:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
選項(xiàng)
這些選項(xiàng)可以讓你控制Jest的行為。雖然Jest的設(shè)計(jì)初衷就是希望能夠零配置實(shí)現(xiàn)測(cè)試舱禽,但有時(shí)候你需要更強(qiáng)大的配置能力指黎。
Jest提供了默認(rèn)選項(xiàng),方便你在必要時(shí)擴(kuò)展他們:
// jest.config.js
const {defaults} = require('jest-config');
module.exports = {
// ...
moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
// ...
};
API列表
automock
[boolean]
默認(rèn)值︰false
這個(gè)選項(xiàng)告訴Jest所有的導(dǎo)入模塊都自動(dòng)mock下.
示例:
// utils.js
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
//__tests__/automocking.test.js
import utils from '../utils';
test('if utils mocked automatically', () => {
// Public methods of `utils` are now mock functions
expect(utils.authorize.mock).toBeTruthy();
expect(utils.isAuthorized.mock).toBeTruthy();
// You can provide them with your own implementation
// or 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 modules當(dāng)源文件下面有mocks目錄時(shí)會(huì)自動(dòng)執(zhí)行mock。核心模塊亚兄,例如
fs
,是不會(huì)默認(rèn)mock的,需要手動(dòng)設(shè)置下:jest.mock('fs')
bail
[number | boolean]
Default: 0
Jest默認(rèn)將所有測(cè)試產(chǎn)生的信息都通過console顯示,bail選項(xiàng)可以讓你配置jest在經(jīng)歷幾次失敗后停止運(yùn)行測(cè)試瞬捕,設(shè)置為true跟設(shè)置1
是一樣的栏账。
browser
[boolean]
默認(rèn)值︰false
當(dāng)解析模塊時(shí),是否遵循在 package.json
中的 Browserify 的 "browser"
字段柠辞。 有些模塊會(huì)導(dǎo)出不一樣的版本,這取決于你是在 Node 還是在一個(gè)瀏覽器中進(jìn)行操作。
cacheDirectory
[string]
默認(rèn)值︰ "/tmp/<path>"
Jest用來儲(chǔ)存依賴信息緩存的目錄菲嘴。
Jest 嘗試去掃描你的依賴樹一次(前期)并且把依賴樹緩存起來,其目的就是抹去某些在運(yùn)行測(cè)試時(shí)需要進(jìn)行的文件系統(tǒng)排序。 這一配置選項(xiàng)讓你可以自定義Jest將緩存數(shù)據(jù)儲(chǔ)存在磁盤的那個(gè)位置龄坪。
clearMocks
[boolean]
默認(rèn)值︰false
在每個(gè)測(cè)試前自動(dòng)清理mock的調(diào)用和實(shí)例instance昭雌。等效于在每個(gè)test之前調(diào)用jest.clearAllMocks
,但不會(huì)刪除已經(jīng)有的mock實(shí)現(xiàn)健田。
collectCoverage
[boolean]
默認(rèn)值︰false
指出是否收集測(cè)試時(shí)的覆蓋率信息烛卧。 由于要帶上覆蓋率搜集語句重新訪問所有執(zhí)行過的文件,這可能會(huì)讓你的測(cè)試執(zhí)行速度被明顯減慢妓局。
collectCoverageFrom
[array]
默認(rèn)值:undefined
參數(shù)是glob patterns 的列表总放,表明哪些集合的文件是需要收集的。如果文件匹配了跟磨,那么就會(huì)被收集作為coverage的基數(shù)间聊,哪怕這個(gè)文件沒有測(cè)試的用例。
示例:
{
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/vendor/**"
]
}
上面的例子中搜索在rootDir下面所有的以js或是jsx為后綴的文件抵拘,同時(shí)派出node_modules
和vendor目錄下的文件哎榴。
注意:該選項(xiàng)要求 collectCoverage
被設(shè)成true,或者通過 --coverage
參數(shù)來調(diào)用 Jest僵蛛。
coverageDirectory
[string]
默認(rèn)值:undefined
Jest輸出覆蓋信息文件的目錄尚蝌。
coveragePathIgnorePatterns
[array<string>]
默認(rèn)值︰["node_modules"]
排除出coverage的文件列表, 這些pattern string默認(rèn)匹配全路徑充尉,可以添加<rootDir>
token來放置有些系統(tǒng)環(huán)境里面把你的覆蓋文件遺漏了飘言。例如:["<rootDir>/build/", "<rootDir>/node_modules/"]
.
coverageProvider
[string]
聲明到底用哪個(gè)provider來用于指導(dǎo)代碼的覆蓋測(cè)試,允許的參數(shù)有babel
(default) 或是 v8
驼侠。
注意:v8
還處于試驗(yàn)階段姿鸿,相比babel的配置可能會(huì)有一些瑕疵。
coverageReporters
[array<string>]
Default: ["json", "lcov", "text", "clover"]
列出包含reporter名字的列表倒源,而Jest會(huì)用他們來生成覆蓋報(bào)告苛预。至于reporter有哪些,請(qǐng)參考:istanbul reporter .
coverageThreshold
[object]
默認(rèn)值:undefined
這個(gè)閾值是作為覆蓋結(jié)構(gòu)的最小閾值來設(shè)置的笋熬∪饶常可以被設(shè)置為global
glob,或是目錄及文件路徑。如果沒有達(dá)到閾值胳螟,Jest 執(zhí)行測(cè)試時(shí)將會(huì)失敗昔馋。 如果給了個(gè)正數(shù),那么就表示是最小的百分比值糖耸,如果給了個(gè)負(fù)數(shù)就表示最大的未被覆蓋的允許值秘遏。
舉個(gè)例子,下面的配置我們?cè)O(shè)置了branch分支數(shù)和函數(shù)覆蓋率小于80%蔬捷,和10%的上限未覆蓋statements
{
...
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
}
}
dependencyExtractor
[string]
默認(rèn)值:undefined
這個(gè)選項(xiàng)允許特定依賴提取器的使用垄提,必須滿足是一個(gè)node module榔袋,同時(shí)導(dǎo)出的object中包含extract
函數(shù)。
例如:
const fs = require('fs');
const crypto = require('crypto');
module.exports = {
extract(code, filePath, defaultExtract) {
const deps = defaultExtract(code, filePath);
// Scan the file and add dependencies in `deps` (which is a `Set`)
return deps;
},
getCacheKey() {
return crypto
.createHash('md5')
.update(fs.readFileSync(__filename))
.digest('hex');
},
};
extract
函數(shù)應(yīng)該要返回一個(gè)code里面依賴項(xiàng)铡俐,并且返回結(jié)果是可以遍歷的.(例如 Array
, Set
, etc.) 凰兑。
同時(shí)module還要包含一個(gè)getCacheKey
函數(shù)來生成一個(gè)緩存的key,用于決定邏輯是否變更审丘。
displayName
[string, object]
默認(rèn)值:undefined
允許在測(cè)試允許的時(shí)候打印顯示標(biāo)簽吏够。這在有多個(gè)repo和多個(gè)jest配置文件的時(shí)候很好用。
module.exports = {
displayName: 'CLIENT',
};
或
module.exports = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
errorOnDeprecated
[boolean]
默認(rèn)值︰false
針對(duì)過期的API拋出提示性的錯(cuò)誤信息滩报。
extraGlobals
[array<string>]
默認(rèn)值:undefined
Test files run inside a vm, which slows calls to global context properties (e.g. Math
). With this option you can specify extra properties to be defined inside the vm for faster lookups.
For example, if your tests call Math
often, you can pass it by setting extraGlobals
.
{
...
"jest": {
"extraGlobals": ["Math"]
}
}
forceCoverageMatch
[array<string>]
Default: ['']
Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage.
For example, if you have tests in source files named with .t.js
extension as following:
// sum.t.js
export function sum(a, b) {
return a + b;
}
if (process.env.NODE_ENV === 'test') {
test('sum', () => {
expect(sum(1, 2)).toBe(3);
});
}
你可以通過設(shè)置 forceCoverageMatch
從這些文件中收集覆蓋率锅知。
{
...
"jest": {
"forceCoverageMatch": ["**/*.t.js"]
}
}
globals
[object]
默認(rèn)值:{}
一組全局變量,在所有測(cè)試環(huán)境下都可以訪問脓钾。
例如售睹,下面這段代碼將為所有測(cè)試環(huán)境創(chuàng)建一個(gè)值為true
的全局變量__DEV__
:
{
...
"jest": {
"globals": {
"__DEV__": true
}
}
}
注意,如果你在這指定了一個(gè)全局引用值(例如可训,對(duì)象或者數(shù)組)昌妹,之后在測(cè)試運(yùn)行中有些代碼改變了這個(gè)被引用的值,這個(gè)改動(dòng)對(duì)于其他測(cè)試不會(huì)生效握截。 In addition the globals
object must be json-serializable, so it can't be used to specify global functions. 要實(shí)現(xiàn)這種功能飞崖,應(yīng)該使用 setupFiles
。
globalSetup
[string]
默認(rèn)值:undefined
This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's globalConfig
object as a parameter.
Note: A global setup module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
Note: Any global variables that are defined through globalSetup
can only be read in globalTeardown
. You cannot retrieve globals defined here in your test suites.
Note: While code transformation is applied to the linked setup-file, Jest will not transform any code in node_modules
. This is due to the need to load the actual transformers (e.g. babel
or typescript
) to perform transformation.
示例:
// setup.js
module.exports = async () => {
// ...
// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
};
// teardown.js
module.exports = async function() {
await global.__MONGOD__.stop();
};
globalTeardown
[string]
默認(rèn)值:undefined
This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's globalConfig
object as a parameter.
Note: A global teardown module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
Note: The same caveat concerning transformation of node_modules
as for globalSetup
applies to globalTeardown
.
maxConcurrency
[number]
Default: 5
A number limiting the number of tests that are allowed to run at the same time when using test.concurrent
. Any test above this limit will be queued and executed once a slot is released.
moduleDirectories
[array<string>]
默認(rèn)值︰["node_modules"]
An array of directory names to be searched recursively up from the requiring module's location. Setting this option will override the default, if you wish to still search node_modules
for packages include it along with any other options: ["node_modules", "bower_components"]
moduleFileExtensions
[array<string>]
Default: ["js", "json", "jsx", "ts", "tsx", "node"]
An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for, in left-to-right order.
We recommend placing the extensions most commonly used in your project on the left, so if you are using TypeScript, you may want to consider moving "ts" and/or "tsx" to the beginning of the array.
moduleNameMapper
[object<string, string>]
默認(rèn)值︰null
A map from regular expressions to module names that allow to stub out resources, like images or styles with a single module.
Modules that are mapped to an alias are unmocked by default, regardless of whether automocking is enabled or not.
Use <rootDir>
string token to refer to rootDir
value if you want to use file paths.
Additionally, you can substitute captured regex groups using numbered backreferences.
示例:
{
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
"module_name_(.*)": "<rootDir>/substituted_module_$1.js"
}
}
The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first.
Note: If you provide module name without boundaries ^$
it may cause hard to spot errors. E.g. relay
will replace all modules which contain relay
as a substring in its name: relay
, react-relay
and graphql-relay
will all be pointed to your stub.
modulePathIgnorePatterns
[array<string>]
默認(rèn)值:[]
An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be require()
-able in the test environment.
These pattern strings match against the full path. Use the <rootDir>
string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/"]
.
modulePaths
[array<string>]
默認(rèn)值:[]
An alternative API to setting the NODE_PATH
env variable, modulePaths
is an array of absolute paths to additional locations to search when resolving modules. Use the <rootDir>
string token to include the path to your project's root directory. Example: ["<rootDir>/app/"]
.
notify
[boolean]
默認(rèn)值︰false
Activates notifications for test results.
notifyMode
[string]
Default: failure-change
Specifies notification mode. Requires notify: true
.
Modes
-
always
: always send a notification. -
failure
: send a notification when tests fail. -
success
: send a notification when tests pass. -
change
: send a notification when the status changed. -
success-change
: send a notification when tests pass or once when it fails. -
failure-change
: send a notification when tests fail or once when it passes.
preset
[string]
默認(rèn)值:undefined
A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a jest-preset.json
or jest-preset.js
file at the root.
For example, this preset foo-bar/jest-preset.js
will be configured as follows:
{
"preset": "foo-bar"
}
Presets may also be relative filesystem paths.
{
"preset": "./node_modules/foo-bar/jest-preset.js"
}
prettierPath
[string]
Default: 'prettier'
Sets the path to the prettier
node module used to update inline snapshots.
projects
[array<string | ProjectConfig>]
默認(rèn)值:undefined
When the projects
configuration is provided with an array of paths or glob patterns, Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time.
{
"projects": ["<rootDir>", "<rootDir>/examples/*"]
}
This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance.
The projects feature can also be used to run multiple configurations or multiple runners. For this purpose you can pass an array of configuration objects. For example, to run both tests and ESLint (via jest-runner-eslint) in the same invocation of Jest:
{
"projects": [
{
"displayName": "test"
},
{
"displayName": "lint",
"runner": "jest-runner-eslint",
"testMatch": ["<rootDir>/**/*.js"]
}
]
}
Note: When using multi project runner, it's recommended to add a displayName
for each project. This will show the displayName
of a project next to its tests.
reporters
[array<moduleName | [moduleName, options]>]
默認(rèn)值:undefined
Use this configuration option to add custom reporters to Jest. A custom reporter is a class that implements onRunStart
, onTestStart
, onTestResult
, onRunComplete
methods that will be called when any of those events occurs.
If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, default
can be passed as a module name.
This will override default reporters:
{
"reporters": ["<rootDir>/my-custom-reporter.js"]
}
This will use custom reporter in addition to default reporters that Jest provides:
{
"reporters": ["default", "<rootDir>/my-custom-reporter.js"]
}
Additionally, custom reporters can be configured by passing an options
object as a second argument:
{
"reporters": [
"default",
["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
]
}
Custom reporter modules must define a class that takes a GlobalConfig
and reporter options as constructor arguments:
Example reporter:
// my-custom-reporter.js
class MyCustomReporter {
constructor(globalConfig, options) {
this._globalConfig = globalConfig;
this._options = options;
}
onRunComplete(contexts, results) {
console.log('Custom reporter output:');
console.log('GlobalConfig: ', this._globalConfig);
console.log('Options: ', this._options);
}
}
module.exports = MyCustomReporter;
// or export default MyCustomReporter;
Custom reporters can also force Jest to exit with non-0 code by returning an Error from getLastError()
methods
class MyCustomReporter {
// ...
getLastError() {
if (this._shouldFail) {
return new Error('my-custom-reporter.js reported an error');
}
}
}
For the full list of methods and argument types see Reporter
interface in packages/jest-reporters/src/types.ts
resetMocks
[boolean]
默認(rèn)值︰false
Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks()
before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.
resetModules
[boolean]
默認(rèn)值︰false
By default, each test file gets its own independent module registry. Enabling resetModules
goes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that local module state doesn't conflict between tests. This can be done programmatically using jest.resetModules()
.
resolver
[string]
默認(rèn)值:undefined
This option allows the use of a custom resolver. This resolver must be a node module that exports a function expecting a string as the first argument for the path to resolve and an object with the following structure as the second argument:
{
"basedir": string,
"browser": bool,
"defaultResolver": "function(request, options)",
"extensions": [string],
"moduleDirectory": [string],
"paths": [string],
"rootDir": [string]
}
The function should either return a path to the module that should be resolved or throw an error if the module can't be found.
Note: the defaultResolver passed as options is the jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom one, e.g. (request, options).
restoreMocks
[boolean]
默認(rèn)值︰false
Automatically restore mock state before every test. Equivalent to calling jest.restoreAllMocks()
before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.
rootDir
[string]
Default: The root of the directory containing your Jest config file or the package.json
or the pwd
if no package.json
is found
The root directory that Jest should scan for tests and modules within. If you put your Jest config inside your package.json
and want the root directory to be the root of your repo, the value for this config param will default to the directory of the package.json
.
Oftentimes, you'll want to set this to 'src'
or 'lib'
, corresponding to where in your repository the code is stored.
Note that using '<rootDir>'
as a string token in any other path-based config settings will refer back to this value. So, for example, if you want your setupFiles
config entry to point at the env-setup.js
file at the root of your project, you could set its value to ["<rootDir>/env-setup.js"]
.
roots
[array<string>]
默認(rèn)值︰["<rootDir>"]
A list of paths to directories that Jest should use to search for files in.
There are times where you only want Jest to search in a single sub-directory (such as cases where you have a src/
directory in your repo), but prevent it from accessing the rest of the repo.
Note: While rootDir
is mostly used as a token to be re-used in other configuration options, roots
is used by the internals of Jest to locate test files and source files. This applies also when searching for manual mocks for modules from node_modules
(__mocks__
will need to live in one of the roots
).
Note: By default, roots
has a single entry <rootDir>
but there are cases where you may want to have multiple roots within one project, for example roots: ["<rootDir>/src/", "<rootDir>/tests/"]
.
runner
[string]
Default: "jest-runner"
This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include:
Note: The runner
property value can omit the jest-runner-
prefix of the package name.
To write a test-runner, export a class with which accepts globalConfig
in the constructor, and has a runTests
method with the signature:
async runTests(
tests: Array<Test>,
watcher: TestWatcher,
onStart: OnTestStart,
onResult: OnTestSuccess,
onFailure: OnTestFailure,
options: TestRunnerOptions,
): Promise<void>
If you need to restrict your test-runner to only run in serial rather then being executed in parallel your class should have the property isSerial
to be set as true
.
setupFiles
[array]
默認(rèn)值:[]
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
It's also worth noting that setupFiles
will execute before setupFilesAfterEnv
.
setupFilesAfterEnv
[array]
默認(rèn)值:[]
A list of paths to modules that run some code to configure or set up the testing framework before each test. Since setupFiles
executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.
If you want a path to be relative to the root directory of your project, please include <rootDir>
inside a path's string, like "<rootDir>/a-configs-folder"
.
For example, Jest ships with several plug-ins to jasmine
that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in these modules.
Note: setupTestFrameworkScriptFile
is deprecated in favor of setupFilesAfterEnv
.
Example setupFilesAfterEnv
array in a jest.config.js:
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
};
Example jest.setup.js
file
jest.setTimeout(10000); // in milliseconds
snapshotResolver
[string]
默認(rèn)值:undefined
The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk.
Example snapshot resolver module:
module.exports = {
// resolves from test to snapshot path
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
// resolves from snapshot to test path
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath
.replace('__snapshots__', '__tests__')
.slice(0, -snapshotExtension.length),
// Example test path, used for preflight consistency check of the implementation above
testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};
snapshotSerializers
[array<string>]
默認(rèn)值:[]
A list of paths to snapshot serializer modules Jest should use for snapshot testing.
Jest has default serializers for built-in JavaScript types, HTML elements (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) and for React elements. See snapshot test tutorial for more information.
Example serializer module:
// my-serializer-module
module.exports = {
print(val, serialize, indent) {
return 'Pretty foo: ' + serialize(val.foo);
},
test(val) {
return val && val.hasOwnProperty('foo');
},
};
serialize
is a function that serializes a value using existing plugins.
To use my-serializer-module
as a serializer, configuration would be as follows:
{
...
"jest": {
"snapshotSerializers": ["my-serializer-module"]
}
}
Finally tests would look as follows:
test(() => {
const bar = {
foo: {
x: 1,
y: 2,
},
};
expect(bar).toMatchSnapshot();
});
Rendered snapshot:
Pretty foo: Object {
"x": 1,
"y": 2,
}
To make a dependency explicit instead of implicit, you can call expect.addSnapshotSerializer
to add a module for an individual test file instead of adding its path to snapshotSerializers
in Jest configuration.
testEnvironment
[string]
默認(rèn)值︰"jsdom"
The test environment that will be used for testing. The default environment in Jest is a browser-like environment through jsdom. If you are building a node service, you can use the node
option to use a node-like environment instead.
By adding a @jest-environment
docblock at the top of the file, you can specify another environment to be used for all tests in that file:
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div');
expect(element).not.toBeNull();
});
You can create your own module that will be used for setting up the test environment. The module must export a class with setup
, teardown
and runScript
methods. You can also pass variables from this module to your test suites by assigning them to this.global
object – this will make them available in your test suites as global variables.
The class may optionally expose a handleTestEvent
method to bind to events fired by jest-circus
.
Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with it's value set to an empty string. If the pragma is not present, it will not be present in the object.
Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.
示例:
// my-custom-environment
const NodeEnvironment = require('jest-environment-node');
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
this.testPath = context.testPath;
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();
}
runScript(script) {
return super.runScript(script);
}
handleTestEvent(event, state) {
if (event.name === 'test_start') {
// ...
}
}
}
module.exports = CustomEnvironment;
// my-test-suite
let someGlobalObject;
beforeAll(() => {
someGlobalObject = global.someGlobalObject;
});
testEnvironmentOptions
[Object]
默認(rèn)值:{}
Test environment options that will be passed to the testEnvironment
. The relevant options depend on the environment. For example you can override options given to jsdom such as {userAgent: "Agent/007"}
.
testMatch
[array<string>]
(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
)
The glob patterns Jest uses to detect test files. By default it looks for .js
, .jsx
, .ts
and .tsx
files inside of __tests__
folders, as well as any files with a suffix of .test
or .spec
(e.g. Component.test.js
or Component.spec.js
). It will also find files called test.js
or spec.js
.
See the micromatch package for details of the patterns you can specify.
See also testRegex
[string | array<string>], but note that you cannot specify both options.
testPathIgnorePatterns
[array<string>]
默認(rèn)值︰["node_modules"]
An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped.
These pattern strings match against the full path. Use the <rootDir>
string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"]
.
testRegex
[string | array<string>]
Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
The pattern or patterns Jest uses to detect test files. By default it looks for .js
, .jsx
, .ts
and .tsx
files inside of __tests__
folders, as well as any files with a suffix of .test
or .spec
(e.g. Component.test.js
or Component.spec.js
). It will also find files called test.js
or spec.js
. See also testMatch
[array<string>], but note that you cannot specify both options.
The following is a visualization of the default regex:
├── __tests__
│ └── component.spec.js # test
│ └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test
Note: testRegex
will try to detect test files using the absolute file path therefore having a folder with name that match it will run all the files as tests
testResultsProcessor
[string]
默認(rèn)值:undefined
This option allows the use of a custom results processor. This processor must be a node module that exports a function expecting an object with the following structure as the first argument and return it:
{
"success": bool,
"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
}
},
...
],
"perfStats": {
"start": epoch,
"end": epoch
},
"testFilePath": absolute path to test file,
"coverage": {}
},
...
]
}
testRunner
[string]
默認(rèn)值︰jasmine2
This option allows use of a custom test runner. The default is jasmine2. A custom test runner can be provided by specifying a path to a test runner implementation.
The test runner module must export a function with the following signature:
function testRunner(
config: Config,
environment: Environment,
runtime: Runtime,
testPath: string,
): Promise<TestResult>;
An example of such function can be found in our default jasmine2 test runner package.
testSequencer
[string]
Default: @jest/test-sequencer
This option allows you to use a custom sequencer instead of Jest's default. sort
may optionally return a Promise.
示例:
Sort test path alphabetically.
const Sequencer = require('@jest/test-sequencer').default;
class CustomSequencer extends Sequencer {
sort(tests) {
// Test structure information
// https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
const copyTests = Array.from(tests);
return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
}
}
module.exports = CustomSequencer;
testURL
[string]
Default: http://localhost
This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
.
timers
[string]
默認(rèn)值︰real
Setting this value to fake
allows the use of fake timers for functions such as setTimeout
. Fake timers are useful when a piece of code sets a long timeout that we don't want to wait for in a test.
transform
[object<string, pathToTransformer | [pathToTransformer, object]>]
默認(rèn)值:undefined
A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that isn't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the examples/typescript example or the webpack tutorial.
Examples of such compilers include:
- Babel
- TypeScript
- async-to-gen
- To build your own please visit the Custom Transformer section
You can pass configuration to a transformer like {filePattern: ['path-to-transformer', {options}]}
For example, to configure babel-jest for non-default behavior, {"\\.js$": ['babel-jest', {rootMode: "upward"}]}
Note: a transformer is only run once per file unless the file has changed. During development of a transformer it can be useful to run Jest with --no-cache
to frequently delete Jest's cache.
Note: if you are using the babel-jest
transformer and want to use an additional code preprocessor, keep in mind that when "transform" is overwritten in any way the babel-jest
is not loaded automatically anymore. If you want to use it to compile JavaScript code it has to be explicitly defined. See babel-jest plugin
transformIgnorePatterns
[array<string>]
默認(rèn)值︰["node_modules"]
An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed.
These pattern strings match against the full path. Use the <rootDir>
string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.
Example: ["<rootDir>/bower_components/", "<rootDir>/node_modules/"]
.
Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules
are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns
to whitelist such modules. You'll find a good example of this use case in React Native Guide.
unmockedModulePathPatterns
[array<string>]
默認(rèn)值:[]
An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader.
This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like underscore/lo-dash, etc). It's generally a best practice to keep this list as small as possible and always use explicit jest.mock()
/jest.unmock()
calls in individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test will run in.
It is possible to override this setting in individual tests by explicitly calling jest.mock()
at the top of the test file.
verbose
[boolean]
默認(rèn)值︰false
Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution.
watchPathIgnorePatterns
[array<string>]
默認(rèn)值:[]
An array of RegExp patterns that are matched against all source file paths before re-running tests in watch mode. If the file path matches any of the patterns, when it is updated, it will not trigger a re-run of tests.
These patterns match against the full path. Use the <rootDir>
string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/node_modules/"]
.
watchPlugins
[array<string | [string, Object]>]
默認(rèn)值:[]
This option allows you to use a custom watch plugins. Read more about watch plugins here.
Examples of watch plugins include:
jest-watch-master
jest-watch-select-projects
jest-watch-suspend
jest-watch-typeahead
jest-watch-yarn-workspaces
Note: The values in the watchPlugins
property value can omit the jest-watch-
prefix of the package name.
//
[string]
No default
This option allow comments in package.json
. Include the comment text as the value of this key anywhere in package.json
.
示例:
{
"name": "my-project",
"jest": {
"http://": "Comment goes here",
"verbose": true
}
}