diff --git a/CHANGELOG.md b/CHANGELOG.md index 2de2ca13883e..75cb22eb8cc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ### Features +### Fixes + +### Chore & Maintenance + +### Performance + +## 26.5.0 + +### Features + - `[jest-circus, jest-config, jest-runtime]` Add new `injectGlobals` config and CLI option to disable injecting global variables into the runtime ([#10484](https://github.com/facebook/jest/pull/10484)) - `[jest-each]` Fixes `.each` type to always be callable ([#10447](https://github.com/facebook/jest/pull/10447)) - `[jest-runner]` Add support for `moduleLoader`s with `default` exports ([#10541](https://github.com/facebook/jest/pull/10541)) @@ -19,8 +29,6 @@ - `[jest-resolve]` Replace read-pkg-up with escalade package ([10558](https://github.com/facebook/jest/pull/10558)) - `[jest-environment-jsdom]` Update jsdom to 16.4.0 ([10578](https://github.com/facebook/jest/pull/10578)) -### Performance - ## 26.4.2 ### Fixes diff --git a/website/versioned_docs/version-26.5/CLI.md b/website/versioned_docs/version-26.5/CLI.md new file mode 100644 index 000000000000..9a507aa197fc --- /dev/null +++ b/website/versioned_docs/version-26.5/CLI.md @@ -0,0 +1,363 @@ +--- +id: version-26.5-cli +title: Jest CLI Options +original_id: cli +--- + +The `jest` command line runner has a number of useful options. You can run `jest --help` to view all available options. Many of the options shown below can also be used together to run tests exactly the way you want. Every one of Jest's [Configuration](Configuration.md) options can also be specified through the CLI. + +Here is a brief overview: + +## Running from the command line + +Run all tests (default): + +```bash +jest +``` + +Run only the tests that were specified with a pattern or filename: + +```bash +jest my-test #or +jest path/to/my-test.js +``` + +Run tests related to changed files based on hg/git (uncommitted files): + +```bash +jest -o +``` + +Run tests related to `path/to/fileA.js` and `path/to/fileB.js`: + +```bash +jest --findRelatedTests path/to/fileA.js path/to/fileB.js +``` + +Run tests that match this spec name (match against the name in `describe` or `test`, basically). + +```bash +jest -t name-of-spec +``` + +Run watch mode: + +```bash +jest --watch #runs jest -o by default +jest --watchAll #runs all tests +``` + +Watch mode also enables to specify the name or path to a file to focus on a specific set of tests. + +## Using with yarn + +If you run Jest via `yarn test`, you can pass the command line arguments directly as Jest arguments. + +Instead of: + +```bash +jest -u -t="ColorPicker" +``` + +you can use: + +```bash +yarn test -u -t="ColorPicker" +``` + +## Using with npm scripts + +If you run Jest via `npm test`, you can still use the command line arguments by inserting a `--` between `npm test` and the Jest arguments. + +Instead of: + +```bash +jest -u -t="ColorPicker" +``` + +you can use: + +```bash +npm test -- -u -t="ColorPicker" +``` + +## Camelcase & dashed args support + +Jest supports both camelcase and dashed arg formats. The following examples will have an equal result: + +```bash +jest --collect-coverage +jest --collectCoverage +``` + +Arguments can also be mixed: + +```bash +jest --update-snapshot --detectOpenHandles +``` + +## Options + +_Note: CLI options take precedence over values from the [Configuration](Configuration.md)._ + + + +--- + +## Reference + +### `jest ` + +When you run `jest` with an argument, that argument is treated as a regular expression to match against files in your project. It is possible to run test suites by providing a pattern. Only the files that the pattern matches will be picked up and executed. Depending on your terminal, you may need to quote this argument: `jest "my.*(complex)?pattern"`. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. + +### `--bail` + +Alias: `-b`. Exit the test suite immediately upon `n` number of failing test suite. Defaults to `1`. + +### `--cache` + +Whether to use the cache. Defaults to true. Disable the cache using `--no-cache`. _Note: the cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower._ + +If you want to inspect the cache, use `--showConfig` and look at the `cacheDirectory` value. If you need to clear the cache, use `--clearCache`. + +### `--changedFilesWithAncestor` + +Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to `--onlyChanged`. + +### `--changedSince` + +Runs tests related to the changes since the provided branch. If the current branch has diverged from the given branch, then only changes made locally will be tested. Behaves similarly to `--onlyChanged`. + +### `--ci` + +When this option is provided, Jest will assume it is running in a CI environment. This changes the behavior when a new snapshot is encountered. Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with `--updateSnapshot`. + +### `--clearCache` + +Deletes the Jest cache directory and then exits without running tests. Will delete `cacheDirectory` if the option is passed, or Jest's default cache directory. The default cache directory can be found by calling `jest --showConfig`. _Note: clearing the cache will reduce performance._ + +### `--collectCoverageFrom=` + +A glob pattern relative to `rootDir` matching the files that coverage info needs to be collected from. + +### `--colors` + +Forces test results output highlighting even if stdout is not a TTY. + +### `--config=` + +Alias: `-c`. The path to a Jest config file specifying how to find and execute tests. If no `rootDir` is set in the config, the directory containing the config file is assumed to be the `rootDir` for the project. This can also be a JSON-encoded value which Jest will use as configuration. + +### `--coverage[=]` + +Alias: `--collectCoverage`. Indicates that test coverage information should be collected and reported in the output. Optionally pass `` to override option set in configuration. + +### `--coverageProvider=` + +Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. + +Note that using `v8` is considered experimental. This uses V8's builtin code coverage rather than one based on Babel. It is not as well tested, and it has also improved in the last few releases of Node. Using the latest versions of node (v14 at the time of this writing) will yield better results. + +### `--debug` + +Print debugging info about your Jest config. + +### `--detectOpenHandles` + +Attempt to collect and print open handles preventing Jest from exiting cleanly. Use this in cases where you need to use `--forceExit` in order for Jest to exit to potentially track down the reason. This implies `--runInBand`, making tests run serially. Implemented using [`async_hooks`](https://nodejs.org/api/async_hooks.html). This option has a significant performance penalty and should only be used for debugging. + +### `--env=` + +The test environment used for all tests. This can point to any file or node module. Examples: `jsdom`, `node` or `path/to/my-environment.js`. + +### `--errorOnDeprecated` + +Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process. + +### `--expand` + +Alias: `-e`. Use this flag to show full diffs and errors instead of a patch. + +### `--findRelatedTests ` + +Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with `--coverage` to include a test coverage for the source files, no duplicate `--collectCoverageFrom` arguments needed. + +### `--forceExit` + +Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up. _Note: This feature is an escape-hatch. If Jest doesn't exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly. You can use `--detectOpenHandles` to help track it down._ + +### `--help` + +Show the help information, similar to this page. + +### `--init` + +Generate a basic configuration file. Based on your project, Jest will ask you a few questions that will help to generate a `jest.config.js` file with a short description for each option. + +### `--injectGlobals` + +Insert Jest's globals (`expect`, `test`, `describe`, `beforeEach` etc.) into the global environment. If you set this to `false`, you should import from `@jest/globals`, e.g. + +```ts +import {expect, jest, test} from '@jest/globals'; + +jest.useFakeTimers(); + +test('some test', () => { + expect(Date.now()).toBe(0); +}); +``` + +_Note: This option is only supported using `jest-circus`._ + +### `--json` + +Prints the test results in JSON. This mode will send all other test output and user messages to stderr. + +### `--outputFile=` + +Write test results to a file when the `--json` option is also specified. The returned JSON structure is documented in [testResultsProcessor](Configuration.md#testresultsprocessor-string). + +### `--lastCommit` + +Run all tests affected by file changes in the last commit made. Behaves similarly to `--onlyChanged`. + +### `--listTests` + +Lists all tests as JSON that Jest will run given the arguments, and exits. This can be used together with `--findRelatedTests` to know which tests Jest will run. + +### `--logHeapUsage` + +Logs the heap usage after every test. Useful to debug memory leaks. Use together with `--runInBand` and `--expose-gc` in node. + +### `--maxConcurrency=` + +Prevents Jest from executing more than the specified amount of tests at the same time. Only affects tests that use `test.concurrent`. + +### `--maxWorkers=|` + +Alias: `-w`. Specifies the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases. + +For environments with variable CPUs available, you can use percentage based configuration: `--maxWorkers=50%` + +### `--noStackTrace` + +Disables stack trace in test results output. + +### `--notify` + +Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing. + +### `--onlyChanged` + +Alias: `-o`. Attempts to identify which tests to run based on which files have changed in the current repository. Only works if you're running tests in a git/hg repository at the moment and requires a static dependency graph (ie. no dynamic requires). + +### `--passWithNoTests` + +Allows the test suite to pass when no files are found. + +### `--projects ... ` + +Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the [`projects`](configuration#projects-arraystring--projectconfig) configuration option. Note that if configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. + +### `--reporters` + +Run tests with specified reporters. [Reporter options](configuration#reporters-arraymodulename--modulename-options) are not available via CLI. Example with multiple reporters: + +`jest --reporters="default" --reporters="jest-junit"` + +### `--runInBand` + +Alias: `-i`. Run all tests serially in the current process, rather than creating a worker pool of child processes that run tests. This can be useful for debugging. + +### `--selectProjects ... ` + +Run only the tests of the specified projects. Jest uses the attribute `displayName` in the configuration to identify each project. If you use this option, you should provide a `displayName` to all your projects. + +### `--runTestsByPath` + +Run only the tests that were specified with their exact paths. + +_Note: The default regex matching works fine on small runs, but becomes slow if provided with multiple patterns and/or against a lot of tests. This option replaces the regex matching logic and by that optimizes the time it takes Jest to filter specific test files_ + +### `--setupTestFrameworkScriptFile=` + +The path to a module that runs some code to configure or set up the testing framework before each test. Beware that files imported by the setup script will not be mocked during testing. + +### `--showConfig` + +Print your Jest config and then exits. + +### `--silent` + +Prevent tests from printing messages through the console. + +### `--testNamePattern=` + +Alias: `-t`. Run only tests with a name that matches the regex. For example, suppose you want to run only tests related to authorization which will have names like `"GET /api/posts with auth"`, then you can use `jest -t=auth`. + +_Note: The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks._ + +### `--testLocationInResults` + +Adds a `location` field to test results. Useful if you want to report the location of a test in a reporter. + +Note that `column` is 0-indexed while `line` is not. + +```json +{ + "column": 4, + "line": 5 +} +``` + +### `--testPathPattern=` + +A regexp pattern string that is matched against all tests paths before executing the test. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. + +### `--testPathIgnorePatterns=[array]` + +An array of regexp pattern strings that are tested against all tests paths before executing the test. Contrary to `--testPathPattern`, it will only run those tests with a path that does not match with the provided regexp expressions. + +### `--testRunner=` + +Lets you specify a custom test runner. + +### `--testSequencer=` + +Lets you specify a custom test sequencer. Please refer to the documentation of the corresponding configuration property for details. + +### `--testTimeout=` + +Default timeout of a test in milliseconds. Default value: 5000. + +### `--updateSnapshot` + +Alias: `-u`. Use this flag to re-record every snapshot that fails during this test run. Can be used together with a test suite pattern or with `--testNamePattern` to re-record snapshots. + +### `--useStderr` + +Divert all output to stderr. + +### `--verbose` + +Display individual test results with the test suite hierarchy. + +### `--version` + +Alias: `-v`. Print the version and exit. + +### `--watch` + +Watch files for changes and rerun tests related to changed files. If you want to re-run all tests when a file has changed, use the `--watchAll` option instead. + +### `--watchAll` + +Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the `--watch` option. + +Use `--watchAll=false` to explicitly disable the watch mode. Note that in most CI environments, this is automatically handled for you. + +### `--watchman` + +Whether to use watchman for file crawling. Defaults to true. Disable using `--no-watchman`. diff --git a/website/versioned_docs/version-26.5/Configuration.md b/website/versioned_docs/version-26.5/Configuration.md new file mode 100644 index 000000000000..2add969e219b --- /dev/null +++ b/website/versioned_docs/version-26.5/Configuration.md @@ -0,0 +1,1294 @@ +--- +id: version-26.5-configuration +title: Configuring Jest +original_id: configuration +--- + +Jest's configuration can be defined in the `package.json` file of your project, or through a `jest.config.js` file or through the `--config ` option. If you'd like to use your `package.json` to store Jest's config, the `"jest"` key should be used on the top level so Jest will know how to find your settings: + +```json +{ + "name": "my-project", + "jest": { + "verbose": true + } +} +``` + +Or through JavaScript: + +```js +// jest.config.js +//Sync object +module.exports = { + verbose: true, +}; + +//Or async function +module.exports = async () => { + return { + verbose: true, + }; +}; +``` + +Please keep in mind that the resulting configuration must be JSON-serializable. + +When using the `--config` option, the JSON file must not contain a "jest" key: + +```json +{ + "bail": 1, + "verbose": true +} +``` + +## Options + +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 + +You can retrieve Jest's default options to expand them if needed: + +```js +// jest.config.js +const {defaults} = require('jest-config'); +module.exports = { + // ... + moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], + // ... +}; +``` + + + +--- + +## Reference + +### `automock` [boolean] + +Default: `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. + +Example: + +```js +// utils.js +export default { + authorize: () => { + return 'token'; + }, + isAuthorized: secret => secret === 'wizard', +}; +``` + +```js +//__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(); +}); +``` + +_Note: Node modules are automatically mocked when you have a manual mock in place (e.g.: `__mocks__/lodash.js`). More info [here](manual-mocks.html#mocking-node-modules)._ + +_Note: Core modules, like `fs`, are not mocked by default. They can be mocked explicitly, like `jest.mock('fs')`._ + +### `bail` [number | boolean] + +Default: `0` + +By default, Jest runs all tests and produces all errors into the console upon completion. The bail config option can be used here to have Jest stop running tests after `n` failures. Setting bail to `true` is the same as setting bail to `1`. + +### `cacheDirectory` [string] + +Default: `"/tmp/"` + +The directory where Jest should store its cached dependency information. + +Jest attempts to scan your dependency tree once (up-front) and cache it in order to ease some of the filesystem raking that needs to happen while running tests. This config option lets you customize where Jest stores that cache data on disk. + +### `clearMocks` [boolean] + +Default: `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] + +Default: `false` + +Indicates whether the coverage information should be collected while executing the test. Because these retrofits all executed files with coverage collection statements, it may significantly slow down your tests. + +### `collectCoverageFrom` [array] + +Default: `undefined` + +An array of [glob patterns](https://github.com/jonschlinkert/micromatch) 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. + +Example: + +```json +{ + "collectCoverageFrom": [ + "**/*.{js,jsx}", + "!**/node_modules/**", + "!**/vendor/**" + ] +} +``` + +This will collect coverage information for all the files inside the project's `rootDir`, except the ones that match `**/node_modules/**` or `**/vendor/**`. + +_Note: This option requires `collectCoverage` to be set to true or Jest to be invoked with `--coverage`._ + +
+ Help: + If you are seeing coverage output such as... + +``` +=============================== Coverage summary =============================== +Statements : Unknown% ( 0/0 ) +Branches : Unknown% ( 0/0 ) +Functions : Unknown% ( 0/0 ) +Lines : Unknown% ( 0/0 ) +================================================================================ +Jest: Coverage data for global was not found. +``` + +Most likely your glob patterns are not matching any files. Refer to the [micromatch](https://github.com/jonschlinkert/micromatch) documentation to ensure your globs are compatible. + +
+ +### `coverageDirectory` [string] + +Default: `undefined` + +The directory where Jest should output its coverage files. + +### `coveragePathIgnorePatterns` [array\] + +Default: `["/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 `` 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: `["/build/", "/node_modules/"]`. + +### `coverageProvider` [string] + +Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. + +Note that using `v8` is considered experimental. This uses V8's builtin code coverage rather than one based on Babel. It is not as well tested, and it has also improved in the last few releases of Node. Using the latest versions of node (v14 at the time of this writing) will yield better results. + +### `coverageReporters` [array\] + +Default: `["json", "lcov", "text", "clover"]` + +A list of reporter names that Jest uses when writing coverage reports. Any [istanbul reporter](https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib) 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._ + +_Note: You can pass additional options to the istanbul reporter using the tuple form. For example:_ + +```json +["json", ["lcov", {"projectRoot": "../../"}]] +``` + +For the additional information about the options object shape you can refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/master/packages/jest-types/src/Config.ts). + +### `coverageThreshold` [object] + +Default: `undefined` + +This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as `global`, as a [glob](https://github.com/isaacs/node-glob#glob-primer), and as a directory or file path. If thresholds aren't met, jest will fail. 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: + +```json +{ + ... + "jest": { + "coverageThreshold": { + "global": { + "branches": 80, + "functions": 80, + "lines": 80, + "statements": -10 + } + } + } +} +``` + +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. Thresholds for globs are applied to all files matching the glob. If the file specified by path is not found, an error is returned. + +For example, with the following configuration: + +```json +{ + ... + "jest": { + "coverageThreshold": { + "global": { + "branches": 50, + "functions": 50, + "lines": 50, + "statements": 50 + }, + "./src/components/": { + "branches": 40, + "statements": 40 + }, + "./src/reducers/**/*.js": { + "statements": 90 + }, + "./src/api/very-important-module.js": { + "branches": 100, + "functions": 100, + "lines": 100, + "statements": 100 + } + } + } +} +``` + +Jest will fail if: + +- 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. +- The `./src/api/very-important-module.js` file has less than 100% coverage. +- Every remaining file combined has less than 50% coverage (`global`). + +### `dependencyExtractor` [string] + +Default: `undefined` + +This option allows the use of a custom dependency extractor. It must be a node module that exports an object with an `extract` function. E.g.: + +```javascript +const fs = require('fs'); +const crypto = require('crypto'); + +module.exports = { + extract(code, filePath, defaultExtract) { + const deps = defaultExtract(code, filePath); + // Scan the file and add dependencies in `deps` (which is a `Set`) + return deps; + }, + getCacheKey() { + return crypto + .createHash('md5') + .update(fs.readFileSync(__filename)) + .digest('hex'); + }, +}; +``` + +The `extract` function should return an iterable (`Array`, `Set`, etc.) with the dependencies found in the code. + +That module can also contain a `getCacheKey` function to generate a cache key to determine if the logic has changed and any cached artifacts relying on it should be discarded. + +### `displayName` [string, object] + +default: `undefined` + +Allows for a label to be printed alongside a test while it is running. This becomes more useful in multi-project repositories where there can be many jest configuration files. This visually tells which project a test belongs to. Here are sample valid values. + +```js +module.exports = { + displayName: 'CLIENT', +}; +``` + +or + +```js +module.exports = { + displayName: { + name: 'CLIENT', + color: 'blue', + }, +}; +``` + +As a secondary option, an object with the properties `name` and `color` can be passed. This allows for a custom configuration of the background color of the displayName. `displayName` defaults to white when its value is a string. Jest uses [chalk](https://github.com/chalk/chalk) to provide the color. As such, all of the valid options for colors supported by chalk are also supported by jest. + +### `errorOnDeprecated` [boolean] + +Default: `false` + +Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process. + +### `extraGlobals` [array\] + +Default: `undefined` + +Test files run inside a [vm](https://nodejs.org/api/vm.html), 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`. + +```json +{ + ... + "jest": { + "extraGlobals": ["Math"] + } +} +``` + +### `forceCoverageMatch` [array\] + +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: + +```javascript +// 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); + }); +} +``` + +You can collect coverage from those files with setting `forceCoverageMatch`. + +```json +{ + ... + "jest": { + "forceCoverageMatch": ["**/*.t.js"] + } +} +``` + +### `globals` [object] + +Default: `{}` + +A set of global variables that need to be available in all test environments. + +For example, the following would create a global `__DEV__` variable set to `true` in all test environments: + +```json +{ + ... + "jest": { + "globals": { + "__DEV__": true + } + } +} +``` + +Note that, if you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will _not_ be persisted across test runs for other test files. In addition, the `globals` object must be json-serializable, so it can't be used to specify global functions. For that, you should use `setupFiles`. + +### `globalSetup` [string] + +Default: `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._ + +Example: + +```js +// setup.js +module.exports = async () => { + // ... + // Set reference to mongod in order to close the server during teardown. + global.__MONGOD__ = mongod; +}; +``` + +```js +// teardown.js +module.exports = async function () { + await global.__MONGOD__.stop(); +}; +``` + +### `globalTeardown` [string] + +Default: `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`._ + +### `injectGlobals` [boolean] + +Default: `true` + +Insert Jest's globals (`expect`, `test`, `describe`, `beforeEach` etc.) into the global environment. If you set this to `false`, you should import from `@jest/globals`, e.g. + +```ts +import {expect, jest, test} from '@jest/globals'; + +jest.useFakeTimers(); + +test('some test', () => { + expect(Date.now()).toBe(0); +}); +``` + +_Note: This option is only supported using `jest-circus`._ + +### `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\] + +Default: `["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\] + +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\>] + +Default: `null` + +A map from regular expressions to module names or to arrays of 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 `` string token to refer to [`rootDir`](#rootdir-string) value if you want to use file paths. + +Additionally, you can substitute captured regex groups using numbered backreferences. + +Example: + +```json +{ + "moduleNameMapper": { + "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub", + "^[./a-zA-Z0-9$_-]+\\.png$": "/RelativeImageStub.js", + "module_name_(.*)": "/substituted_module_$1.js", + "assets/(.*)": [ + "/images/$1", + "/photos/$1", + "/recipes/$1" + ] + } +} +``` + +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. This is true for arrays of module names as well. + +_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\] + +Default: `[]` + +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 `` 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: `["/build/"]`. + +### `modulePaths` [array\] + +Default: `[]` + +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 `` string token to include the path to your project's root directory. Example: `["/app/"]`. + +### `notify` [boolean] + +Default: `false` + +Activates notifications for test results. + +**Beware:** Jest uses [node-notifier](https://github.com/mikaelbr/node-notifier) to display desktop notifications. On Windows, it creates a new start menu entry on the first use and not display the notification. Notifications will be properly displayed on subsequent runs + +### `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] + +Default: `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: + +```json +{ + "preset": "foo-bar" +} +``` + +Presets may also be relative to filesystem paths. + +```json +{ + "preset": "./node_modules/foo-bar/jest-preset.js" +} +``` + +### `prettierPath` [string] + +Default: `'prettier'` + +Sets the path to the [`prettier`](https://prettier.io/) node module used to update inline snapshots. + +### `projects` [array\] + +Default: `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. + +```json +{ + "projects": ["", "/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](#runner-string). For this purpose, you can pass an array of configuration objects. For example, to run both tests and ESLint (via [jest-runner-eslint](https://github.com/jest-community/jest-runner-eslint)) in the same invocation of Jest: + +```json +{ + "projects": [ + { + "displayName": "test" + }, + { + "displayName": "lint", + "runner": "jest-runner-eslint", + "testMatch": ["/**/*.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\] + +Default: `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: + +```json +{ + "reporters": ["/my-custom-reporter.js"] +} +``` + +This will use custom reporter in addition to default reporters that Jest provides: + +```json +{ + "reporters": ["default", "/my-custom-reporter.js"] +} +``` + +Additionally, custom reporters can be configured by passing an `options` object as a second argument: + +```json +{ + "reporters": [ + "default", + ["/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: + +```js +// 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 + +```js +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](https://github.com/facebook/jest/blob/master/packages/jest-reporters/src/types.ts) + +### `resetMocks` [boolean] + +Default: `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] + +Default: `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 the local module state doesn't conflict between tests. This can be done programmatically using [`jest.resetModules()`](JestObjectAPI.md#jestresetmodules). + +### `resolver` [string] + +Default: `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: + +```json +{ + "basedir": string, + "defaultResolver": "function(request, options)", + "extensions": [string], + "moduleDirectory": [string], + "paths": [string], + "packageFilter": "function(pkg, pkgdir)", + "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 an option 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)`. + +For example, if you want to respect Browserify's [`"browser"` field](https://github.com/browserify/browserify-handbook/blob/master/readme.markdown#browser-field), you can use the following configuration: + +```json +{ + ... + "jest": { + "resolver": "browser-resolve" + } +} +``` + +By combining `defaultResolver` and `packageFilter` we can implement a `package.json` "pre-processor" that allows us to change how the default resolver will resolve modules. For example, imagine we want to use the field `"module"` if it is present, otherwise fallback to `"main"`: + +```json +{ + ... + "jest": { + "resolver": "my-module-resolve" + } +} +``` + +```js +// my-module-resolve package + +module.exports = (request, options) => { + // Call the defaultResolver, so we leverage its cache, error handling, etc. + return options.defaultResolver(request, { + ...options, + // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb) + packageFilter: pkg => { + return { + ...pkg, + // Alter the value of `main` before resolving the package + main: pkg.module || pkg.main, + }; + }, + }); +}; +``` + +### `restoreMocks` [boolean] + +Default: `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`](http://en.wikipedia.org/wiki/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 `''` 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`](#setupfiles-array) config entry to point at the `env-setup.js` file at the root of your project, you could set its value to `["/env-setup.js"]`._ + +### `roots` [array\] + +Default: `[""]` + +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 `` but there are cases where you may want to have multiple roots within one project, for example `roots: ["/src/", "/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: + +- [`jest-runner-eslint`](https://github.com/jest-community/jest-runner-eslint) +- [`jest-runner-mocha`](https://github.com/rogeliog/jest-runner-mocha) +- [`jest-runner-tsc`](https://github.com/azz/jest-runner-tsc) +- [`jest-runner-prettier`](https://github.com/keplersj/jest-runner-prettier) + +_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: + +```ts +async runTests( + tests: Array, + watcher: TestWatcher, + onStart: OnTestStart, + onResult: OnTestSuccess, + onFailure: OnTestFailure, + options: TestRunnerOptions, +): Promise +``` + +If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property `isSerial` to be set as `true`. + +### `setupFiles` [array] + +Default: `[]` + +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). + +### `setupFilesAfterEnv` [array] + +Default: `[]` + +A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed. Since [`setupFiles`](#setupfiles-array) 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](#rootdir-string), please include `` inside a path's string, like `"/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: + +```js +module.exports = { + setupFilesAfterEnv: ['./jest.setup.js'], +}; +``` + +Example `jest.setup.js` file + +```js +jest.setTimeout(10000); // in milliseconds +``` + +### `slowTestThreshold` [number] + +Default: `5` + +The number of seconds after which a test is considered as slow and reported as such in the results. + +### `snapshotResolver` [string] + +Default: `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: + +```js +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\] + +Default: `[]` + +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](TutorialReactNative.md#snapshot-test) for more information. + +Example serializer module: + +```js +// my-serializer-module +module.exports = { + serialize(val, config, indentation, depth, refs, printer) { + return 'Pretty foo: ' + printer(val.foo); + }, + + test(val) { + return val && val.hasOwnProperty('foo'); + }, +}; +``` + +`printer` is a function that serializes a value using existing plugins. + +To use `my-serializer-module` as a serializer, configuration would be as follows: + +```json +{ + ... + "jest": { + "snapshotSerializers": ["my-serializer-module"] + } +} +``` + +Finally tests would look as follows: + +```js +test(() => { + const bar = { + foo: { + x: 1, + y: 2, + }, + }; + + expect(bar).toMatchSnapshot(); +}); +``` + +Rendered snapshot: + +```json +Pretty foo: Object { + "x": 1, + "y": 2, +} +``` + +To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. + +More about serializers API can be found [here](https://github.com/facebook/jest/tree/master/packages/pretty-format/README.md#serialize). + +### `testEnvironment` [string] + +Default: `"jsdom"` + +The test environment that will be used for testing. The default environment in Jest is a browser-like environment through [jsdom](https://github.com/jsdom/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: + +```js +/** + * @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 an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/master/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/master/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. + +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._ + +Example: + +```js +// 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); + } + + async handleTestEvent(event, state) { + if (event.name === 'test_start') { + // ... + } + } +} + +module.exports = CustomEnvironment; +``` + +```js +// my-test-suite +let someGlobalObject; + +beforeAll(() => { + someGlobalObject = global.someGlobalObject; +}); +``` + +### `testEnvironmentOptions` [Object] + +Default: `{}` + +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](https://github.com/jsdom/jsdom) such as `{userAgent: "Agent/007"}`. + +### `testFailureExitCode` [number] + +Default: `1` + +The exit code Jest returns on test failure. + +_Note: This does not change the exit code in the case of Jest errors (e.g. invalid configuration)._ + +### `testMatch` [array\] + +(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](https://github.com/jonschlinkert/micromatch) package for details of the patterns you can specify. + +See also [`testRegex` [string | array\]](#testregex-string--arraystring), but note that you cannot specify both options. + +### `testPathIgnorePatterns` [array\] + +Default: `["/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 `` 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: `["/build/", "/node_modules/"]`. + +### `testRegex` [string | array\] + +Default: `(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$` + +The pattern or patterns Jest uses to detect test files. By default it looks for `.js`, `.jsx`, `.ts` and `.tsx` files inside of `__tests__` folders, as well as any files with a suffix of `.test` or `.spec` (e.g. `Component.test.js` or `Component.spec.js`). It will also find files called `test.js` or `spec.js`. See also [`testMatch` [array\]](#testmatch-arraystring), but note that you cannot specify both options. + +The following is a visualization of the default regex: + +```bash +├── __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 a name that matches it will run all the files as tests_ + +### `testResultsProcessor` [string] + +Default: `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: + +```json +{ + "success": bool, + "startTime": epoch, + "numTotalTestSuites": number, + "numPassedTestSuites": number, + "numFailedTestSuites": number, + "numRuntimeErrorTestSuites": number, + "numTotalTests": number, + "numPassedTests": number, + "numFailedTests": number, + "numPendingTests": number, + "numTodoTests": number, + "openHandles": Array, + "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] + +Default: `jasmine2` + +This option allows the 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: + +```ts +function testRunner( + globalConfig: GlobalConfig, + config: ProjectConfig, + environment: Environment, + runtime: Runtime, + testPath: string, +): Promise; +``` + +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/master/packages/jest-jasmine2/src/index.ts). + +### `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. + +Example: + +Sort test path alphabetically. + +```js +// testSequencer.js +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; +``` + +Use it in your Jest config file like this: + +```json +{ + "testSequencer": "path/to/testSequencer.js" +} +``` + +### `testTimeout` [number] + +Default: `5000` + +Default timeout of a test in milliseconds. + +### `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] + +Default: `real` + +Setting this value to `legacy` or `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. + +If the value is `modern`, [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers) will be used as implementation instead of Jest's own legacy implementation. This will be the default fake implementation in Jest 27. + +### `transform` [object\] + +Default: `{"^.+\\.[jt]sx?$": "babel-jest"}` + +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 aren'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](https://github.com/facebook/jest/blob/master/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). + +Examples of such compilers include: + +- [Babel](https://babeljs.io/) +- [TypeScript](http://www.typescriptlang.org/) +- [async-to-gen](http://github.com/leebyron/async-to-gen#jest) +- To build your own please visit the [Custom Transformer](TutorialReact.md#custom-transformers) 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 the development of a transformer it can be useful to run Jest with `--no-cache` to frequently [delete Jest's cache](Troubleshooting.md#caching-issues)._ + +_Note: when adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"^.+\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/facebook/jest/tree/master/packages/babel-jest#setup)_ + +### `transformIgnorePatterns` [array\] + +Default: `["/node_modules/", "\\.pnp\\.[^\\\/]+$"]` + +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 `` 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: `["/bower_components/", "/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 allow transpiling such modules. You'll find a good example of this use case in [React Native Guide](https://jestjs.io/docs/en/tutorial-react-native#transformignorepatterns-customization). + +### `unmockedModulePathPatterns` [array\] + +Default: `[]` + +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] + +Default: `false` + +Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. Note that if there is only one test file being run it will default to `true`. + +### `watchPathIgnorePatterns` [array\] + +Default: `[]` + +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 `` 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: `["/node_modules/"]`. + +Even if nothing is specified here, the watcher will ignore changes to any hidden files and directories, i.e. files and folders that begin with a dot (`.`). + +### `watchPlugins` [array\] + +Default: `[]` + +This option allows you to use custom watch plugins. Read more about watch plugins [here](watch-plugins). + +Examples of watch plugins include: + +- [`jest-watch-master`](https://github.com/rickhanlonii/jest-watch-master) +- [`jest-watch-select-projects`](https://github.com/rogeliog/jest-watch-select-projects) +- [`jest-watch-suspend`](https://github.com/unional/jest-watch-suspend) +- [`jest-watch-typeahead`](https://github.com/jest-community/jest-watch-typeahead) +- [`jest-watch-yarn-workspaces`](https://github.com/cameronhunter/jest-watch-directories/tree/master/packages/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 allows comments in `package.json`. Include the comment text as the value of this key anywhere in `package.json`. + +Example: + +```json +{ + "name": "my-project", + "jest": { + "//": "Comment goes here", + "verbose": true + } +} +``` diff --git a/website/versioned_docs/version-26.5/GettingStarted.md b/website/versioned_docs/version-26.5/GettingStarted.md new file mode 100644 index 000000000000..e813c7993d0f --- /dev/null +++ b/website/versioned_docs/version-26.5/GettingStarted.md @@ -0,0 +1,183 @@ +--- +id: version-26.5-getting-started +title: Getting Started +original_id: getting-started +--- + +Install Jest using [`yarn`](https://yarnpkg.com/en/package/jest): + +```bash +yarn add --dev jest +``` + +Or [`npm`](https://www.npmjs.com/package/jest): + +```bash +npm install --save-dev jest +``` + +Note: Jest documentation uses `yarn` commands, but `npm` will also work. You can compare `yarn` and `npm` commands in the [yarn docs, here](https://yarnpkg.com/en/docs/migrating-from-npm#toc-cli-commands-comparison). + +Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a `sum.js` file: + +```javascript +function sum(a, b) { + return a + b; +} +module.exports = sum; +``` + +Then, create a file named `sum.test.js`. This will contain our actual test: + +```javascript +const sum = require('./sum'); + +test('adds 1 + 2 to equal 3', () => { + expect(sum(1, 2)).toBe(3); +}); +``` + +Add the following section to your `package.json`: + +```json +{ + "scripts": { + "test": "jest" + } +} +``` + +Finally, run `yarn test` or `npm run test` and Jest will print this message: + +```bash +PASS ./sum.test.js +✓ adds 1 + 2 to equal 3 (5ms) +``` + +**You just successfully wrote your first test using Jest!** + +This test used `expect` and `toBe` to test that two values were exactly identical. To learn about the other things that Jest can test, see [Using Matchers](UsingMatchers.md). + +## Running from command line + +You can run Jest directly from the CLI (if it's globally available in your `PATH`, e.g. by `yarn global add jest` or `npm install jest --global`) with a variety of useful options. + +Here's how to run Jest on files matching `my-test`, using `config.json` as a configuration file and display a native OS notification after the run: + +```bash +jest my-test --notify --config=config.json +``` + +If you'd like to learn more about running `jest` through the command line, take a look at the [Jest CLI Options](CLI.md) page. + +## Additional Configuration + +### Generate a basic configuration file + +Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option: + +```bash +jest --init +``` + +### Using Babel + +To use [Babel](http://babeljs.io/), install required dependencies via `yarn`: + +```bash +yarn add --dev babel-jest @babel/core @babel/preset-env +``` + +Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: + +```javascript +// babel.config.js +module.exports = { + presets: [ + [ + '@babel/preset-env', + { + targets: { + node: 'current', + }, + }, + ], + ], +}; +``` + +**The ideal configuration for Babel will depend on your project.** See [Babel's docs](https://babeljs.io/docs/en/) for more details. + +
Making your Babel config jest-aware + +Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. + +```javascript +// babel.config.js +module.exports = api => { + const isTest = api.env('test'); + // You can use isTest to determine what presets and plugins to use. + + return { + // ... + }; +}; +``` + +> Note: `babel-jest` is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the `transform` configuration option: + +```javascript +// jest.config.js +module.exports = { + transform: {}, +}; +``` + +
+ +
Babel 6 support + +Jest 24 dropped support for Babel 6. We highly recommend you to upgrade to Babel 7, which is actively maintained. However, if you cannot upgrade to Babel 7, either keep using Jest 23 or upgrade to Jest 24 with `babel-jest` locked at version 23, like in the example below: + +``` +"dependencies": { + "babel-core": "^6.26.3", + "babel-jest": "^23.6.0", + "babel-preset-env": "^1.7.0", + "jest": "^24.0.0" +} +``` + +While we generally recommend using the same version of every Jest package, this workaround will allow you to continue using the latest version of Jest with Babel 6 for now. + +
+ +### Using webpack + +Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the [webpack guide](Webpack.md) to get started. + +### Using parcel + +Jest can be used in projects that use [parcel-bundler](https://parceljs.org/) to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official [docs](https://parceljs.org/getting_started.html) to get started. + +### Using TypeScript + +Jest supports TypeScript, via Babel. First, make sure you followed the instructions on [using Babel](#using-babel) above. Next, install the `@babel/preset-typescript` via `yarn`: + +```bash +yarn add --dev @babel/preset-typescript +``` + +Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. + +```diff +// babel.config.js +module.exports = { + presets: [ + ['@babel/preset-env', {targets: {node: 'current'}}], ++ '@babel/preset-typescript', + ], +}; +``` + +However, there are some [caveats](https://babeljs.io/docs/en/next/babel-plugin-transform-typescript.html#caveats) to using TypeScript with Babel. Because TypeScript support in Babel is transpilation, Jest will not type-check your tests as they are run. If you want that, you can use [ts-jest](https://github.com/kulshekhar/ts-jest). diff --git a/website/versioned_docs/version-26.5/MockFunctions.md b/website/versioned_docs/version-26.5/MockFunctions.md new file mode 100644 index 000000000000..ea0b8f5328e1 --- /dev/null +++ b/website/versioned_docs/version-26.5/MockFunctions.md @@ -0,0 +1,282 @@ +--- +id: version-26.5-mock-functions +title: Mock Functions +original_id: mock-functions +--- + +Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with `new`, and allowing test-time configuration of return values. + +There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a [`manual mock`](ManualMocks.md) to override a module dependency. + +## Using a mock function + +Let's imagine we're testing an implementation of a function `forEach`, which invokes a callback for each item in a supplied array. + +```javascript +function forEach(items, callback) { + for (let index = 0; index < items.length; index++) { + callback(items[index]); + } +} +``` + +To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected. + +```javascript +const mockCallback = jest.fn(x => 42 + x); +forEach([0, 1], mockCallback); + +// The mock function is called twice +expect(mockCallback.mock.calls.length).toBe(2); + +// The first argument of the first call to the function was 0 +expect(mockCallback.mock.calls[0][0]).toBe(0); + +// The first argument of the second call to the function was 1 +expect(mockCallback.mock.calls[1][0]).toBe(1); + +// The return value of the first call to the function was 42 +expect(mockCallback.mock.results[0].value).toBe(42); +``` + +## `.mock` property + +All mock functions have this special `.mock` property, which is where data about how the function has been called and what the function returned is kept. The `.mock` property also tracks the value of `this` for each call, so it is possible to inspect this as well: + +```javascript +const myMock = jest.fn(); + +const a = new myMock(); +const b = {}; +const bound = myMock.bind(b); +bound(); + +console.log(myMock.mock.instances); +// > [ , ] +``` + +These mock members are very useful in tests to assert how these functions get called, instantiated, or what they returned: + +```javascript +// The function was called exactly once +expect(someMockFunction.mock.calls.length).toBe(1); + +// The first arg of the first call to the function was 'first arg' +expect(someMockFunction.mock.calls[0][0]).toBe('first arg'); + +// The second arg of the first call to the function was 'second arg' +expect(someMockFunction.mock.calls[0][1]).toBe('second arg'); + +// The return value of the first call to the function was 'return value' +expect(someMockFunction.mock.results[0].value).toBe('return value'); + +// This function was instantiated exactly twice +expect(someMockFunction.mock.instances.length).toBe(2); + +// The object returned by the first instantiation of this function +// had a `name` property whose value was set to 'test' +expect(someMockFunction.mock.instances[0].name).toEqual('test'); +``` + +## Mock Return Values + +Mock functions can also be used to inject test values into your code during a test: + +```javascript +const myMock = jest.fn(); +console.log(myMock()); +// > undefined + +myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true); + +console.log(myMock(), myMock(), myMock(), myMock()); +// > 10, 'x', true, true +``` + +Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate the behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. + +```javascript +const filterTestFn = jest.fn(); + +// Make the mock return `true` for the first call, +// and `false` for the second call +filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false); + +const result = [11, 12].filter(num => filterTestFn(num)); + +console.log(result); +// > [11] +console.log(filterTestFn.mock.calls); +// > [ [11], [12] ] +``` + +Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. + +## Mocking Modules + +Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: + +```js +// users.js +import axios from 'axios'; + +class Users { + static all() { + return axios.get('/users.json').then(resp => resp.data); + } +} + +export default Users; +``` + +Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the `jest.mock(...)` function to automatically mock the axios module. + +Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. + +```js +// users.test.js +import axios from 'axios'; +import Users from './users'; + +jest.mock('axios'); + +test('should fetch users', () => { + const users = [{name: 'Bob'}]; + const resp = {data: users}; + axios.get.mockResolvedValue(resp); + + // or you could use the following depending on your use case: + // axios.get.mockImplementation(() => Promise.resolve(resp)) + + return Users.all().then(data => expect(data).toEqual(users)); +}); +``` + +## Mock Implementations + +Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. + +```javascript +const myMockFn = jest.fn(cb => cb(null, true)); + +myMockFn((err, val) => console.log(val)); +// > true +``` + +The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: + +```js +// foo.js +module.exports = function () { + // some implementation; +}; + +// test.js +jest.mock('../foo'); // this happens automatically with automocking +const foo = require('../foo'); + +// foo is a mock function +foo.mockImplementation(() => 42); +foo(); +// > 42 +``` + +When you need to recreate a complex behavior of a mock function such that multiple function calls produce different results, use the `mockImplementationOnce` method: + +```javascript +const myMockFn = jest + .fn() + .mockImplementationOnce(cb => cb(null, true)) + .mockImplementationOnce(cb => cb(null, false)); + +myMockFn((err, val) => console.log(val)); +// > true + +myMockFn((err, val) => console.log(val)); +// > false +``` + +When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): + +```javascript +const myMockFn = jest + .fn(() => 'default') + .mockImplementationOnce(() => 'first call') + .mockImplementationOnce(() => 'second call'); + +console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); +// > 'first call', 'second call', 'default', 'default' +``` + +For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: + +```javascript +const myObj = { + myMethod: jest.fn().mockReturnThis(), +}; + +// is the same as + +const otherObj = { + myMethod: jest.fn(function () { + return this; + }), +}; +``` + +## Mock Names + +You can optionally provide a name for your mock functions, which will be displayed instead of "jest.fn()" in the test error output. Use this if you want to be able to quickly identify the mock function reporting an error in your test output. + +```javascript +const myMockFn = jest + .fn() + .mockReturnValue('default') + .mockImplementation(scalar => 42 + scalar) + .mockName('add42'); +``` + +## Custom Matchers + +Finally, in order to make it less demanding to assert how mock functions have been called, we've added some custom matcher functions for you: + +```javascript +// The mock function was called at least once +expect(mockFunc).toHaveBeenCalled(); + +// The mock function was called at least once with the specified args +expect(mockFunc).toHaveBeenCalledWith(arg1, arg2); + +// The last call to the mock function was called with the specified args +expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2); + +// All calls and the name of the mock is written as a snapshot +expect(mockFunc).toMatchSnapshot(); +``` + +These matchers are sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: + +```javascript +// The mock function was called at least once +expect(mockFunc.mock.calls.length).toBeGreaterThan(0); + +// The mock function was called at least once with the specified args +expect(mockFunc.mock.calls).toContainEqual([arg1, arg2]); + +// The last call to the mock function was called with the specified args +expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([ + arg1, + arg2, +]); + +// The first arg of the last call to the mock function was `42` +// (note that there is no sugar helper for this specific of an assertion) +expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1][0]).toBe(42); + +// A snapshot will check that a mock was invoked the same number of times, +// in the same order, with the same arguments. It will also assert on the name. +expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]); +expect(mockFunc.getMockName()).toBe('a mock name'); +``` + +For a complete list of matchers, check out the [reference docs](ExpectAPI.md). diff --git a/website/versioned_docs/version-26.5/MongoDB.md b/website/versioned_docs/version-26.5/MongoDB.md new file mode 100644 index 000000000000..753a3167c180 --- /dev/null +++ b/website/versioned_docs/version-26.5/MongoDB.md @@ -0,0 +1,62 @@ +--- +id: version-26.5-mongodb +title: Using with MongoDB +original_id: mongodb +--- + +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). + +## Use jest-mongodb Preset + +[Jest MongoDB](https://github.com/shelfio/jest-mongodb) provides all required configuration to run your tests using MongoDB. + +1. First install `@shelf/jest-mongodb` + +``` +yarn add @shelf/jest-mongodb --dev +``` + +2. Specify preset in your Jest configuration: + +```json +{ + "preset": "@shelf/jest-mongodb" +} +``` + +3. Write your test + +```js +const {MongoClient} = require('mongodb'); + +describe('insert', () => { + let connection; + let db; + + beforeAll(async () => { + connection = await MongoClient.connect(global.__MONGO_URI__, { + useNewUrlParser: true, + }); + db = await connection.db(global.__MONGO_DB_NAME__); + }); + + afterAll(async () => { + await connection.close(); + await db.close(); + }); + + it('should insert a doc into collection', async () => { + const users = db.collection('users'); + + const mockUser = {_id: 'some-user-id', name: 'John'}; + await users.insertOne(mockUser); + + const insertedUser = await users.findOne({_id: 'some-user-id'}); + expect(insertedUser).toEqual(mockUser); + }); +}); +``` + +There's no need to load any dependencies. + +See [documentation](https://github.com/shelfio/jest-mongodb) for details (configuring MongoDB version, etc). diff --git a/website/versions.json b/website/versions.json index 995c100b74ee..14f8caf68ea5 100644 --- a/website/versions.json +++ b/website/versions.json @@ -1,4 +1,5 @@ [ + "26.5", "26.4", "26.2", "26.0",