Jest 的配置可以通过项目中的 package.json 文件、jest.config.js 文件或者 —config <path/to/js|json> 选项来指定 如果你倾向于在 package.json 文件中处理 Jest 配置参数,那么 「jest」属性需要放到最外层,才能被 Jest 正确识别。

  1. {
  2. "name": "my-project",
  3. "jest": {
  4. "verbose": true
  5. }
  6. }

或者通过 JavaScript:

  1. // jest.config.js
  2. module.exports = {
  3. verbose: true,
  4. };

请记住最后拿到的配置必须是可被 JSON 序列化的。

使用—config配置选项时,JSON 文件绝不能有"jest"键值︰

  1. {
  2. "bail": true,
  3. "verbose": true
  4. }

选项

These options let you control Jest's behavior in your package.json file. The Jest philosophy is to work great by default, but sometimes you just need more configuration power.

Defaults

您可以了解 Jest 的默认选项,以便在必要时扩展它们:

  1. // jest.config.js
  2. const {defaults} = require('jest-config');
  3. module.exports = {
  4. // ...
  5. moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  6. // ...
  7. };

参考

automock [boolean]

默认值︰false

This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface.

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. isAuthorized: secret => secret === 'wizard',
  7. };
  1. //__tests__/automocking.test.js
  2. import utils from '../utils';
  3. test('if utils mocked automatically', () => {
  4. // Public methods of `utils` are now mock functions
  5. expect(utils.authorize.mock).toBeTruthy();
  6. expect(utils.isAuthorized.mock).toBeTruthy();
  7. // You can provide them with your own implementation
  8. // or just pass the expected return value
  9. utils.authorize.mockReturnValue('mocked_token');
  10. utils.isAuthorized.mockReturnValue(true);
  11. expect(utils.authorize()).toBe('mocked_token');
  12. expect(utils.isAuthorized('not_wizard')).toBeTruthy();
  13. });

Note: Node modules are automatically mocked when you have a manual mock in place (e.g.: mocks/lodash.js). More info here.

Note: Core modules, like fs, are not mocked by default. They can be mocked explicitly, like jest.mock('fs').

bail [boolean]

默认值︰false

By default, Jest runs all tests and produces all errors into the console upon completion. The bail config option can be used here to have Jest stop running tests after the first failure.

browser [boolean]

默认值︰false

当解析模块时,是否遵循在 package.json 中的 Browserify 的 "browser" 字段。 有些模块会导出不一样的版本,这取决于你是在 Node 还是在一个浏览器中进行操作。

cacheDirectory [string]

默认值︰ "/tmp/<path>"

Jest用来储存依赖信息缓存的目录。

Jest 尝试去扫描你的依赖树一次(前期)并且把依赖树缓存起来,其目的就是抹去某些在运行测试时需要进行的文件系统排序。 这一配置选项让你可以自定义Jest将缓存数据储存在磁盘的那个位置。

clearMocks [boolean]

默认值︰false

Automatically clear mock calls and instances before every test. Equivalent to calling jest.clearAllMocks() before each test. This does not remove any mock implementation that may have been provided.

collectCoverage [boolean]

默认值︰false

指出是否收集测试时的覆盖率信息。 由于要带上覆盖率搜集语句重新访问所有执行过的文件,这可能会让你的测试执行速度被明显减慢。

collectCoverageFrom [array]

默认值:undefined

An array of glob patterns indicating a set of files for which coverage information should be collected. If a file matches the specified glob pattern, coverage information will be collected for it even if no tests exist for this file and it's never required in the test suite.

示例:

  1. {
  2. "collectCoverageFrom": [
  3. "**/*.{js,jsx}",
  4. "!**/node_modules/**",
  5. "!**/vendor/**"
  6. ]
  7. }

This will collect coverage information for all the files inside the project's rootDir, except the ones that match /node_modules/ or /vendor/.

注意:该选项要求 collectCoverage 被设成true,或者通过 —coverage 参数来调用 Jest。

Help: If you are seeing coverage output such as…

  1. =============================== Coverage summary ===============================
  2. Statements : Unknown% ( 0/0 )
  3. Branches : Unknown% ( 0/0 )
  4. Functions : Unknown% ( 0/0 )
  5. Lines : Unknown% ( 0/0 )
  6. ================================================================================
  7. Jest: Coverage data for global was not found.

Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.

coverageDirectory [string]

默认值:undefined

Jest输出覆盖信息文件的目录。

coveragePathIgnorePatterns [数组<string>]

默认值︰["node_modules"]

An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped.

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/"].

coverageReporters [数组<string>]

Default: ["json", "lcov", "text", "clover"]

A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.

Note: Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output.

coverageThreshold [object]

默认值:undefined

This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as global, as a glob, and as a directory or file path. 如果没有达到阈值,Jest 执行测试时将会失败。 Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed.

For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements:

  1. {
  2. ...
  3. "jest": {
  4. "coverageThreshold": {
  5. "global": {
  6. "branches": 80,
  7. "functions": 80,
  8. "lines": 80,
  9. "statements": -10
  10. }
  11. }
  12. }
  13. }

If globs or paths are specified alongside global, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. 通配符模式设置的阈值将应用到所匹配的所有文件上并单独计算。 If the file specified by path is not found, error is returned.

例如,基于下面的配置:

  1. {
  2. ...
  3. "jest": {
  4. "coverageThreshold": {
  5. "global": {
  6. "branches": 50,
  7. "functions": 50,
  8. "lines": 50,
  9. "statements": 50
  10. },
  11. "./src/components/": {
  12. "branches": 40,
  13. "statements": 40
  14. },
  15. "./src/reducers/**/*.js": {
  16. "statements": 90
  17. },
  18. "./src/api/very-important-module.js": {
  19. "branches": 100,
  20. "functions": 100,
  21. "lines": 100,
  22. "statements": 100
  23. }
  24. }
  25. }
  26. }

Jest 在以下情况下将失败:

  • The ./src/components directory has less than 40% branch or statement coverage.
  • One of the files matching the ./src/reducers/*/.js glob has less than 90% statement coverage.
  • 文件 ./src/api/very-important-module.js 的任意一种覆盖率低于 100%
  • 所有剩下的文件的任意一种覆盖率总计低于 50% (根据 global)

displayName [string]

默认值:undefined

Allows for a label to be printed along side a test while it is running. This becomes more useful in multiproject repositories where there can be many jest configuration files. This visually tells which project a test belongs to.

errorOnDeprecated [boolean]

默认值︰false

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

forceCoverageMatch [数组<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:

  1. // sum.t.js
  2. export function sum(a, b) {
  3. return a + b;
  4. }
  5. if (process.env.NODE_ENV === 'test') {
  6. test('sum', () => {
  7. expect(sum(1, 2)).toBe(3);
  8. });
  9. }

你可以通过设置 forceCoverageMatch 从这些文件中收集覆盖率。

  1. {
  2. ...
  3. "jest": {
  4. "forceCoverageMatch": ["**/*.t.js"]
  5. }
  6. }

globals [object]

默认值:{}

一组全局变量,在所有测试环境下都可以访问。

例如,下面这段代码将为所有测试环境创建一个值为true的全局变量DEV

  1. {
  2. ...
  3. "jest": {
  4. "globals": {
  5. "__DEV__": true
  6. }
  7. }
  8. }

注意,如果你在这指定了一个全局引用值(例如,对象或者数组),之后在测试运行中有些代码改变了这个被引用的值,这个改动对于其他测试不会生效。 In addition the globals object must be json-serializable, so it can't be used to specify global functions. 要实现这种功能,应该使用 setupFiles

globalSetup [string]

默认值: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.

globalTeardown [string]

默认值: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.

moduleDirectories [数组<string>]

默认值︰["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 [数组<string>]

默认值:["js"、"json"、"jsx"、"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.

If you are using TypeScript, you will want to add "ts" and/or "tsx" to the above default. Where you place these is up to you - we recommend placing the extensions most commonly used in your project on the left.

moduleNameMapper [object<string, string>]

默认值︰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.

示例:

  1. {
  2. "moduleNameMapper": {
  3. "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
  4. "^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
  5. "module_name_(.*)": "<rootDir>/substituted_module_$1.js"
  6. }
  7. }

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 [数组<string>]

默认值:[]

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 [数组<string>]

默认值:[]

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]

默认值︰false

Activates notifications for test results.

notifyMode [string]

Default: always

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 fails or once when it passes.

preset [string]

默认值:undefined

A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a jest-preset.json or jest-preset.js file at the root.

For example, this preset foo-bar/jest-preset.js will be configured as follows:

  1. {
  2. "preset": "foo-bar"
  3. }

Presets may also be relative filesystem paths.

  1. {
  2. "preset": "./node_modules/foo-bar/jest-preset.js"
  3. }

prettierPath [string]

Default: 'prettier'

Sets the path to the prettier node module used to update inline snapshots.

projects [数组<string | projectconfig>]

默认值: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.

  1. {
  2. "projects": ["<rootDir>", "<rootDir>/examples/*"]
  3. }

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:

  1. {
  2. "projects": [
  3. {
  4. "displayName": "test"
  5. },
  6. {
  7. "displayName": "lint",
  8. "runner": "jest-runner-eslint",
  9. "testMatch": ["<rootDir>/**/*.js"]
  10. }
  11. ]
  12. }

Note: When using multi project runner, it's recommended to add a displayName for each project. This will show the displayName of a project next to its tests.

reporters [数组<modulename | [modulename, options]>]

默认值:undefined

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:

  1. {
  2. "reporters": ["<rootDir>/my-custom-reporter.js"]
  3. }

This will use custom reporter in addition to default reporters that Jest provides:

  1. {
  2. "reporters": ["default", "<rootDir>/my-custom-reporter.js"]
  3. }

Additionally, custom reporters can be configured by passing an options object as a second argument:

  1. {
  2. "reporters": [
  3. "default",
  4. ["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
  5. ]
  6. }

Custom reporter modules must define a class that takes a GlobalConfig and reporter options as constructor arguments:

Example reporter:

  1. // my-custom-reporter.js
  2. class MyCustomReporter {
  3. constructor(globalConfig, options) {
  4. this._globalConfig = globalConfig;
  5. this._options = options;
  6. }
  7. onRunComplete(contexts, results) {
  8. console.log('Custom reporter output:');
  9. console.log('GlobalConfig: ', this._globalConfig);
  10. console.log('Options: ', this._options);
  11. }
  12. }
  13. module.exports = MyCustomReporter;

Custom reporters can also force Jest to exit with non-0 code by returning an Error from getLastError() methods

  1. class MyCustomReporter {
  2. // ...
  3. getLastError() {
  4. if (this._shouldFail) {
  5. return new Error('my-custom-reporter.js reported an error');
  6. }
  7. }
  8. }

For the full list of methods and argument types see Reporter interface in packages/jest-reporters/src/types.ts

resetMocks [boolean]

默认值︰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]

默认值︰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]

默认值: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:

  1. {
  2. "basedir": string,
  3. "browser": bool,
  4. "extensions": [string],
  5. "moduleDirectory": [string],
  6. "paths": [string],
  7. "rootDir": [string]
  8. }

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.

restoreMocks [boolean]

默认值︰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 fileor 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 [数组<string>]

默认值︰["<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 nodemodules (_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:

To write a test-runner, export a class with which accepts globalConfig in the constructor, and has a runTests method with the signature:

  1. async runTests(
  2. tests: Array<Test>,
  3. watcher: TestWatcher,
  4. onStart: OnTestStart,
  5. onResult: OnTestSuccess,
  6. onFailure: OnTestFailure,
  7. options: TestRunnerOptions,
  8. ): 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]

默认值:[]

The 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 beforesetupTestFrameworkScriptFile.

setupTestFrameworkScriptFile [string]

默认值:undefined

模块路径是可以在每个测试运行前,通过运行一些代码来配置或设置测试框架。 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 this path to be relative to the root directory of your project, please include <rootDir> inside the path 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 this module.

snapshotSerializers [数组<string>]

默认值:[]

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:

  1. // my-serializer-module
  2. module.exports = {
  3. print(val, serialize, indent) {
  4. return 'Pretty foo: ' + serialize(val.foo);
  5. },
  6. test(val) {
  7. return val && val.hasOwnProperty('foo');
  8. },
  9. };

serialize is a function that serializes a value using existing plugins.

To use my-serializer-module as a serializer, configuration would be as follows:

  1. {
  2. ...
  3. "jest": {
  4. "snapshotSerializers": ["my-serializer-module"]
  5. }
  6. }

Finally tests would look as follows:

  1. test(() => {
  2. const bar = {
  3. foo: {
  4. x: 1,
  5. y: 2,
  6. },
  7. };
  8. expect(bar).toMatchSnapshot();
  9. });

Rendered snapshot:

  1. Pretty foo: Object {
  2. "x": 1,
  3. "y": 2,
  4. }

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]

默认值︰"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:

  1. /**
  2. * @jest-environment jsdom
  3. */
  4. test('use jsdom in this test file', () => {
  5. const element = document.createElement('div');
  6. expect(element).not.toBeNull();
  7. });

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.

Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.

示例:

  1. // my-custom-environment
  2. const NodeEnvironment = require('jest-environment-node');
  3. class CustomEnvironment extends NodeEnvironment {
  4. constructor(config) {
  5. super(config);
  6. }
  7. async setup() {
  8. await super.setup();
  9. await someSetupTasks();
  10. this.global.someGlobalObject = createGlobalObject();
  11. }
  12. async teardown() {
  13. this.global.someGlobalObject = destroyGlobalObject();
  14. await someTeardownTasks();
  15. await super.teardown();
  16. }
  17. runScript(script) {
  18. return super.runScript(script);
  19. }
  20. }
  21. module.exports = CustomEnvironment;
  1. // my-test-suite
  2. let someGlobalObject;
  3. beforeAll(() => {
  4. someGlobalObject = global.someGlobalObject;
  5. });

Note: Jest comes with JSDOM@11 by default. Due to JSDOM 12 and newer dropping support for Node 6, Jest is unable to upgrade for the time being. However, you can install a custom testEnvironment with whichever version of JSDOM you want. E.g. jest-environment-jsdom-thirteen, which has JSDOM@13.

testEnvironmentOptions [Object]

默认值:{}

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 [数组<string>]

(default: [ "/tests//.js?(x)", "**/?(.)+(spec|test).js?(x)" ])

The glob patterns Jest uses to detect test files. By default it looks for .js and .jsx 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], but note that you cannot specify both options.

testPathIgnorePatterns [数组<string>]

默认值︰["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]

默认值:(/tests/.*|(\.|/)(test|spec))\.jsx?$

The pattern Jest uses to detect test files. By default it looks for .js and .jsx 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:

  1. ├── __tests__
  2. └── component.spec.js # test
  3. └── anything # test
  4. ├── package.json # not test
  5. ├── foo.test.js # test
  6. ├── bar.spec.jsx # test
  7. └── component.js # not test

Note: testRegex will try to detect test files using the absolute file path therefore having a folder with name that match it will run all the files as tests

testResultsProcessor [string]

默认值:undefined

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:

  1. {
  2. "success": bool,
  3. "startTime": epoch,
  4. "numTotalTestSuites": number,
  5. "numPassedTestSuites": number,
  6. "numFailedTestSuites": number,
  7. "numRuntimeErrorTestSuites": number,
  8. "numTotalTests": number,
  9. "numPassedTests": number,
  10. "numFailedTests": number,
  11. "numPendingTests": number,
  12. "openHandles": Array<Error>,
  13. "testResults": [{
  14. "numFailingTests": number,
  15. "numPassingTests": number,
  16. "numPendingTests": number,
  17. "testResults": [{
  18. "title": string (message in it block),
  19. "status": "failed" | "pending" | "passed",
  20. "ancestorTitles": [string (message in describe blocks)],
  21. "failureMessages": [string],
  22. "numPassingAsserts": number,
  23. "location": {
  24. "column": number,
  25. "line": number
  26. }
  27. },
  28. ...
  29. ],
  30. "perfStats": {
  31. "start": epoch,
  32. "end": epoch
  33. },
  34. "testFilePath": absolute path to test file,
  35. "coverage": {}
  36. },
  37. ...
  38. ]
  39. }

testRunner [string]

默认值︰jasmine2

This option allows use of a custom test runner. The default is jasmine2. A custom test runner can be provided by specifying a path to a test runner implementation.

The test runner module must export a function with the following signature:

  1. function testRunner(
  2. config: Config,
  3. environment: Environment,
  4. runtime: Runtime,
  5. testPath: string,
  6. ): Promise<TestResult>;

An example of such function can be found in our default jasmine2 test runner package.

testURL [string]

Default: http://localhost

This option sets the URL for the jsdom environment. It is reflected in properties such as location.href.

timers [string]

默认值︰real

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, string>]

默认值: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:

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 [数组<string>]

默认值︰["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 [数组<string>]

默认值:[]

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]

默认值︰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 [数组<string>]

默认值:[]

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 [数组<string | [string, object]>]

默认值:[]

This option allows you to use a custom watch plugins. Read more about watch plugins here.

Examples of watch plugins include: