diff --git a/website/versioned_docs/version-25.1/Configuration.md b/website/versioned_docs/version-25.1/Configuration.md deleted file mode 100644 index 41af1a1b9b47..000000000000 --- a/website/versioned_docs/version-25.1/Configuration.md +++ /dev/null @@ -1,1197 +0,0 @@ ---- -id: version-25.1-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 -module.exports = { - 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`. - -### `browser` [boolean] - -Default: `false` - -Respect Browserify's [`"browser"` field](https://github.com/substack/browserify-handbook#browser-field) in `package.json` when resolving modules. Some modules export different versions based on whether they are operating in Node or a browser. - -### `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 this 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 and comes with a few caveats - -1. Your node version must include `vm.compileFunction`, which was introduced in [node 10.10](https://nodejs.org/dist/latest-v12.x/docs/api/vm.html#vm_vm_compilefunction_code_params_options) -1. Tests needs to run in Node test environment (support for `jsdom` requires [`jest-environment-jsdom-sixteen`](https://www.npmjs.com/package/jest-environment-jsdom-sixteen)) -1. V8 has way better data in the later versions, so using the latest versions of node (v13 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._ - -### `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, 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 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. 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`._ - -### `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 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" - } -} -``` - -The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. - -_Note: If you provide module name without boundaries `^$` it may cause hard to spot errors. E.g. `relay` will replace all modules which contain `relay` as a substring in its name: `relay`, `react-relay` and `graphql-relay` will all be pointed to your stub._ - -### `modulePathIgnorePatterns` [array\] - -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. - -### `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 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 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, - "browser": bool, - "defaultResolver": "function(request, options)", - "extensions": [string], - "moduleDirectory": [string], - "paths": [string], - "rootDir": [string] -} -``` - -The function should either return a path to the module that should be resolved or throw an error if the module can't be found. - -Note: the defaultResolver passed as options is the jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom one, e.g. (request, options). - -### `restoreMocks` [boolean] - -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 then 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 -``` - -### `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#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/tmpvar/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 a `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/master/packages/jest-circus). - -Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with it's value set to an empty string. If the pragma is not present, it will not be present in the object. - -_Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment._ - -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); - } - - 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/tmpvar/jsdom) such as `{userAgent: "Agent/007"}`. - -### `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 name that match 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 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 -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; -``` - -### `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 `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\] - -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 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](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 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/"]` - -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 whitelist 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 begins with a dot (`.`). - -### `watchPlugins` [array\] - -Default: `[]` - -This option allows you to use a 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 allow 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-25.1/TutorialReact.md b/website/versioned_docs/version-25.1/TutorialReact.md deleted file mode 100644 index 6caa36a09575..000000000000 --- a/website/versioned_docs/version-25.1/TutorialReact.md +++ /dev/null @@ -1,341 +0,0 @@ ---- -id: version-25.1-tutorial-react -title: Testing React Apps -original_id: tutorial-react ---- - -At Facebook, we use Jest to test [React](http://facebook.github.io/react/) applications. - -## Setup - -### Setup with Create React App - -If you are new to React, we recommend using [Create React App](https://github.com/facebookincubator/create-react-app). It is ready to use and [ships with Jest](https://facebook.github.io/create-react-app/docs/running-tests#docsNav)! You will only need to add `react-test-renderer` for rendering snapshots. - -Run - -```bash -yarn add --dev react-test-renderer -``` - -### Setup without Create React App - -If you have an existing application you'll need to install a few packages to make everything work well together. We are using the `babel-jest` package and the `react` babel preset to transform our code inside of the test environment. Also see [using babel](GettingStarted.md#using-babel). - -Run - -```bash -yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer -``` - -Your `package.json` should look something like this (where `` is the actual latest version number for the package). Please add the scripts and jest configuration entries: - -```json -// package.json - "dependencies": { - "react": "", - "react-dom": "" - }, - "devDependencies": { - "@babel/preset-env": "", - "@babel/preset-react": "", - "babel-jest": "", - "jest": "", - "react-test-renderer": "" - }, - "scripts": { - "test": "jest" - } -``` - -```js -// babel.config.js -module.exports = { - presets: ['@babel/preset-env', '@babel/preset-react'], -}; -``` - -**And you're good to go!** - -### Snapshot Testing - -Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: - -```javascript -// Link.react.js -import React from 'react'; - -const STATUS = { - HOVERED: 'hovered', - NORMAL: 'normal', -}; - -export default class Link extends React.Component { - constructor(props) { - super(props); - - this._onMouseEnter = this._onMouseEnter.bind(this); - this._onMouseLeave = this._onMouseLeave.bind(this); - - this.state = { - class: STATUS.NORMAL, - }; - } - - _onMouseEnter() { - this.setState({class: STATUS.HOVERED}); - } - - _onMouseLeave() { - this.setState({class: STATUS.NORMAL}); - } - - render() { - return ( - - {this.props.children} - - ); - } -} -``` - -Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file: - -```javascript -// Link.react.test.js -import React from 'react'; -import Link from '../Link.react'; -import renderer from 'react-test-renderer'; - -test('Link changes the class when hovered', () => { - const component = renderer.create( - Facebook, - ); - let tree = component.toJSON(); - expect(tree).toMatchSnapshot(); - - // manually trigger the callback - tree.props.onMouseEnter(); - // re-rendering - tree = component.toJSON(); - expect(tree).toMatchSnapshot(); - - // manually trigger the callback - tree.props.onMouseLeave(); - // re-rendering - tree = component.toJSON(); - expect(tree).toMatchSnapshot(); -}); -``` - -When you run `yarn test` or `jest`, this will produce an output file like this: - -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap -exports[`Link changes the class when hovered 1`] = ` - - Facebook - -`; - -exports[`Link changes the class when hovered 2`] = ` - - Facebook - -`; - -exports[`Link changes the class when hovered 3`] = ` - - Facebook - -`; -``` - -The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. - -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/master/examples/snapshot). - -#### Snapshot Testing with Mocks, Enzyme and React 16 - -There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style: - -```js -jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent'); -``` - -Then you will see warnings in the console: - -```bash -Warning: is using uppercase HTML. Always use lowercase HTML tags in React. - -# Or: -Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. -``` - -React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are: - -1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward: - ```js - jest.mock('./SomeComponent', () => () => 'SomeComponent'); - ``` -2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name. - ```js - jest.mock('./Widget', () => () => ); - ``` -3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme. -4. Disable warnings all together (should be done in your jest setup file): - ```js - jest.mock('fbjs/lib/warning', () => require('fbjs/lib/emptyFunction')); - ``` - This shouldn't normally be your option of choice as useful warnings could be lost. However, in some cases, for example when testing react-native's components we are rendering react-native tags into the DOM and many warnings are irrelevant. Another option is to swizzle the console.warn and suppress specific warnings. - -### DOM Testing - -If you'd like to assert, and manipulate your rendered components you can use [react-testing-library](https://github.com/kentcdodds/react-testing-library), [Enzyme](http://airbnb.io/enzyme/), or React's [TestUtils](http://facebook.github.io/react/docs/test-utils.html). The following two examples use react-testing-library and Enzyme. - -#### react-testing-library - -You have to run `yarn add --dev @testing-library/react` to use react-testing-library. - -Let's implement a checkbox which swaps between two labels: - -```javascript -// CheckboxWithLabel.js - -import React from 'react'; - -export default class CheckboxWithLabel extends React.Component { - constructor(props) { - super(props); - this.state = {isChecked: false}; - - // bind manually because React class components don't auto-bind - // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding - this.onChange = this.onChange.bind(this); - } - - onChange() { - this.setState({isChecked: !this.state.isChecked}); - } - - render() { - return ( - - ); - } -} -``` - -```javascript -// __tests__/CheckboxWithLabel-test.js -import React from 'react'; -import {cleanup, fireEvent, render} from '@testing-library/react'; -import CheckboxWithLabel from '../CheckboxWithLabel'; - -// Note: running cleanup afterEach is done automatically for you in @testing-library/react@9.0.0 or higher -// unmount and cleanup DOM after the test is finished. -afterEach(cleanup); - -it('CheckboxWithLabel changes the text after click', () => { - const {queryByLabelText, getByLabelText} = render( - , - ); - - expect(queryByLabelText(/off/i)).toBeTruthy(); - - fireEvent.click(getByLabelText(/off/i)); - - expect(queryByLabelText(/on/i)).toBeTruthy(); -}); -``` - -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/master/examples/react-testing-library). - -#### Enzyme - -You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React version below 15.5.0, you will also need to install `react-addons-test-utils`. - -Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. - -```javascript -// __tests__/CheckboxWithLabel-test.js - -import React from 'react'; -import {shallow} from 'enzyme'; -import CheckboxWithLabel from '../CheckboxWithLabel'; - -test('CheckboxWithLabel changes the text after click', () => { - // Render a checkbox with label in the document - const checkbox = shallow(); - - expect(checkbox.text()).toEqual('Off'); - - checkbox.find('input').simulate('change'); - - expect(checkbox.text()).toEqual('On'); -}); -``` - -The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). - -### Custom transformers - -If you need more advanced functionality, you can also build your own transformer. Instead of using babel-jest, here is an example of using babel: - -```javascript -// custom-transformer.js -'use strict'; - -const {transform} = require('@babel/core'); -const jestPreset = require('babel-preset-jest'); - -module.exports = { - process(src, filename) { - const result = transform(src, { - filename, - presets: [jestPreset], - }); - - return result ? result.code : src; - }, -}; -``` - -Don't forget to install the `@babel/core` and `babel-preset-jest` packages for this example to work. - -To make this work with Jest you need to update your Jest configuration with this: `"transform": {"\\.js$": "path/to/custom-transformer.js"}`. - -If you'd like to build a transformer with babel support, you can also use babel-jest to compose one and pass in your custom configuration options: - -```javascript -const babelJest = require('babel-jest'); - -module.exports = babelJest.createTransformer({ - presets: ['my-custom-preset'], -}); -``` diff --git a/website/versioned_docs/version-25.3/JestObjectAPI.md b/website/versioned_docs/version-25.3/JestObjectAPI.md deleted file mode 100644 index 849304a96b75..000000000000 --- a/website/versioned_docs/version-25.3/JestObjectAPI.md +++ /dev/null @@ -1,672 +0,0 @@ ---- -id: version-25.3-jest-object -title: The Jest Object -original_id: jest-object ---- - -The `jest` object is automatically in scope within every test file. The methods in the `jest` object help create mocks and let you control Jest's overall behavior. - -## Mock Modules - -### `jest.disableAutomock()` - -Disables automatic mocking in the module loader. - -> See `automock` section of [configuration](Configuration.md#automock-boolean) for more information - -After this method is called, all `require()`s will return the real versions of each module (rather than a mocked version). - -Jest configuration: - -```json -{ - "automock": true -} -``` - -Example: - -```js -// utils.js -export default { - authorize: () => { - return 'token'; - }, -}; -``` - -```js -// __tests__/disableAutomocking.js -import utils from '../utils'; - -jest.disableAutomock(); - -test('original implementation', () => { - // now we have the original implementation, - // even if we set the automocking in a jest configuration - expect(utils.authorize()).toBe('token'); -}); -``` - -This is usually useful when you have a scenario where the number of dependencies you want to mock is far less than the number of dependencies that you don't. For example, if you're writing a test for a module that uses a large number of dependencies that can be reasonably classified as "implementation details" of the module, then you likely do not want to mock them. - -Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. Array.prototype methods) to highly common utility methods (e.g. underscore/lo-dash, array utilities etc) and entire libraries like React.js. - -Returns the `jest` object for chaining. - -_Note: this method was previously called `autoMockOff`. When using `babel-jest`, calls to `disableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOff` if you want to explicitly avoid this behavior._ - -### `jest.enableAutomock()` - -Enables automatic mocking in the module loader. - -Returns the `jest` object for chaining. - -> See `automock` section of [configuration](Configuration.md#automock-boolean) for more information - -Example: - -```js -// utils.js -export default { - authorize: () => { - return 'token'; - }, - isAuthorized: secret => secret === 'wizard', -}; -``` - -```js -// __tests__/disableAutomocking.js -jest.enableAutomock(); - -import utils from '../utils'; - -test('original implementation', () => { - // now we have the mocked implementation, - expect(utils.authorize._isMockFunction).toBeTruthy(); - expect(utils.isAuthorized._isMockFunction).toBeTruthy(); -}); -``` - -_Note: this method was previously called `autoMockOn`. When using `babel-jest`, calls to `enableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOn` if you want to explicitly avoid this behavior._ - -### `jest.genMockFromModule(moduleName)` - -Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you. - -This is useful when you want to create a [manual mock](ManualMocks.md) that extends the automatic mock's behavior. - -Example: - -```js -// utils.js -export default { - authorize: () => { - return 'token'; - }, - isAuthorized: secret => secret === 'wizard', -}; -``` - -```js -// __tests__/genMockFromModule.test.js -const utils = jest.genMockFromModule('../utils').default; -utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); - -test('implementation created by jest.genMockFromModule', () => { - expect(utils.authorize.mock).toBeTruthy(); - expect(utils.isAuthorized('not wizard')).toEqual(true); -}); -``` - -This is how `genMockFromModule` will mock the following data types: - -#### `Function` - -Creates a new [mock function](https://jestjs.io/docs/en/mock-functions.html). The new function has no formal parameters and when called will return `undefined`. This functionality also applies to `async` functions. - -#### `Class` - -Creates new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked. - -#### `Object` - -Creates a new deeply cloned object. The object keys are maintained and their values are mocked. - -#### `Array` - -Creates a new empty array, ignoring the original. - -#### `Primitives` - -Creates a new property with the same primitive value as the original property. - -Example: - -``` -// example.js -module.exports = { - function: function square(a, b) { - return a * b; - }, - asyncFunction: async function asyncSquare(a, b) { - const result = await a * b; - return result; - }, - class: new class Bar { - constructor() { - this.array = [1, 2, 3]; - } - foo() {} - }, - object: { - baz: 'foo', - bar: { - fiz: 1, - buzz: [1, 2, 3], - }, - }, - array: [1, 2, 3], - number: 123, - string: 'baz', - boolean: true, - symbol: Symbol.for('a.b.c'), -}; -``` - -```js -// __tests__/example.test.js -const example = jest.genMockFromModule('./example'); - -test('should run example code', () => { - // creates a new mocked function with no formal arguments. - expect(example.function.name).toEqual('square'); - expect(example.function.length).toEqual(0); - - // async functions get the same treatment as standard synchronous functions. - expect(example.asyncFunction.name).toEqual('asyncSquare'); - expect(example.asyncFunction.length).toEqual(0); - - // creates a new class with the same interface, member functions and properties are mocked. - expect(example.class.constructor.name).toEqual('Bar'); - expect(example.class.foo.name).toEqual('foo'); - expect(example.class.array.length).toEqual(0); - - // creates a deeply cloned version of the original object. - expect(example.object).toEqual({ - baz: 'foo', - bar: { - fiz: 1, - buzz: [], - }, - }); - - // creates a new empty array, ignoring the original array. - expect(example.array.length).toEqual(0); - - // creates a new property with the same primitive value as the original property. - expect(example.number).toEqual(123); - expect(example.string).toEqual('baz'); - expect(example.boolean).toEqual(true); - expect(example.symbol).toEqual(Symbol.for('a.b.c')); -}); -``` - -### `jest.mock(moduleName, factory, options)` - -Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: - -```js -// banana.js -module.exports = () => 'banana'; - -// __tests__/test.js -jest.mock('../banana'); - -const banana = require('../banana'); // banana will be explicitly mocked. - -banana(); // will return 'undefined' because the function is auto-mocked. -``` - -The second argument can be used to specify an explicit module factory that is being run instead of using Jest's automocking feature: - -```js -jest.mock('../moduleName', () => { - return jest.fn(() => 42); -}); - -// This runs the function specified as second argument to `jest.mock`. -const moduleName = require('../moduleName'); -moduleName(); // Will return '42'; -``` - -When using the `factory` parameter for an ES6 module with a default export, the `__esModule: true` property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it's an instruction to import the property named `default` from the export object: - -```js -import moduleName, {foo} from '../moduleName'; - -jest.mock('../moduleName', () => { - return { - __esModule: true, - default: jest.fn(() => 42), - foo: jest.fn(() => 43), - }; -}); - -moduleName(); // Will return 42 -foo(); // Will return 43 -``` - -The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system: - -```js -jest.mock( - '../moduleName', - () => { - /* - * Custom implementation of a module that doesn't exist in JS, - * like a generated module or a native module in react-native. - */ - }, - {virtual: true}, -); -``` - -> **Warning:** Importing a module in a setup file (as specified by `setupTestFrameworkScriptFile`) will prevent mocking for the module in question, as well as all the modules that it imports. - -Modules that are mocked with `jest.mock` are mocked only for the file that calls `jest.mock`. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module. - -Returns the `jest` object for chaining. - -### `jest.unmock(moduleName)` - -Indicates that the module system should never return a mocked version of the specified module from `require()` (e.g. that it should always return the real module). - -The most common use of this API is for specifying the module a given test intends to be testing (and thus doesn't want automatically mocked). - -Returns the `jest` object for chaining. - -### `jest.doMock(moduleName, factory, options)` - -When using `babel-jest`, calls to `mock` will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior. - -One example when this is useful is when you want to mock a module differently within the same file: - -```js -beforeEach(() => { - jest.resetModules(); -}); - -test('moduleName 1', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 1); - }); - const moduleName = require('../moduleName'); - expect(moduleName()).toEqual(1); -}); - -test('moduleName 2', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 2); - }); - const moduleName = require('../moduleName'); - expect(moduleName()).toEqual(2); -}); -``` - -Using `jest.doMock()` with ES6 imports requires additional steps. Follow these if you don't want to use `require` in your tests: - -- We have to specify the `__esModule: true` property (see the [`jest.mock()`](#jestmockmodulename-factory-options) API for more information). -- Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using `import()`. -- Finally, we need an environment which supports dynamic importing. Please see [Using Babel](GettingStarted.md#using-babel) for the initial setup. Then add the plugin [babel-plugin-dynamic-import-node](https://www.npmjs.com/package/babel-plugin-dynamic-import-node), or an equivalent, to your Babel config to enable dynamic importing in Node. - -```js -beforeEach(() => { - jest.resetModules(); -}); - -test('moduleName 1', () => { - jest.doMock('../moduleName', () => { - return { - __esModule: true, - default: 'default1', - foo: 'foo1', - }; - }); - return import('../moduleName').then(moduleName => { - expect(moduleName.default).toEqual('default1'); - expect(moduleName.foo).toEqual('foo1'); - }); -}); - -test('moduleName 2', () => { - jest.doMock('../moduleName', () => { - return { - __esModule: true, - default: 'default2', - foo: 'foo2', - }; - }); - return import('../moduleName').then(moduleName => { - expect(moduleName.default).toEqual('default2'); - expect(moduleName.foo).toEqual('foo2'); - }); -}); -``` - -Returns the `jest` object for chaining. - -### `jest.dontMock(moduleName)` - -When using `babel-jest`, calls to `unmock` will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior. - -Returns the `jest` object for chaining. - -### `jest.setMock(moduleName, moduleExports)` - -Explicitly supplies the mock object that the module system should return for the specified module. - -On occasion there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normally under those circumstances you should write a [manual mock](ManualMocks.md) that is more adequate for the module in question. However, on extremely rare occasions, even a manual mock isn't suitable for your purposes and you need to build the mock yourself inside your test. - -In these rare scenarios you can use this API to manually fill the slot in the module system's mock-module registry. - -Returns the `jest` object for chaining. - -_Note It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object._ - -### `jest.requireActual(moduleName)` - -Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. - -Example: - -```js -jest.mock('../myModule', () => { - // Require the original module to not be mocked... - const originalModule = jest.requireActual(moduleName); - - return { - __esModule: true, // Use it when dealing with esModules - ...originalModule, - getRandom: jest.fn().mockReturnValue(10), - }; -}); - -const getRandom = require('../myModule').getRandom; - -getRandom(); // Always returns 10 -``` - -### `jest.requireMock(moduleName)` - -Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. - -### `jest.resetModules()` - -Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. - -Example: - -```js -const sum1 = require('../sum'); -jest.resetModules(); -const sum2 = require('../sum'); -sum1 === sum2; -// > false (Both sum modules are separate "instances" of the sum module.) -``` - -Example in a test: - -```js -beforeEach(() => { - jest.resetModules(); -}); - -test('works', () => { - const sum = require('../sum'); -}); - -test('works too', () => { - const sum = require('../sum'); - // sum is a different copy of the sum module from the previous test. -}); -``` - -Returns the `jest` object for chaining. - -### `jest.isolateModules(fn)` - -`jest.isolateModules(fn)` goes a step further than `jest.resetModules()` and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests. - -```js -let myModule; -jest.isolateModules(() => { - myModule = require('myModule'); -}); - -const otherCopyOfMyModule = require('myModule'); -``` - -## Mock functions - -### `jest.fn(implementation)` - -Returns a new, unused [mock function](MockFunctionAPI.md). Optionally takes a mock implementation. - -```js -const mockFn = jest.fn(); -mockFn(); -expect(mockFn).toHaveBeenCalled(); - -// With a mock implementation: -const returnsTrue = jest.fn(() => true); -console.log(returnsTrue()); // true; -``` - -### `jest.isMockFunction(fn)` - -Determines if the given function is a mocked function. - -### `jest.spyOn(object, methodName)` - -Creates a mock function similar to `jest.fn` but also tracks calls to `object[methodName]`. Returns a Jest [mock function](MockFunctionAPI.md). - -_Note: By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation);`_ - -Example: - -```js -const video = { - play() { - return true; - }, -}; - -module.exports = video; -``` - -Example test: - -```js -const video = require('./video'); - -test('plays video', () => { - const spy = jest.spyOn(video, 'play'); - const isPlaying = video.play(); - - expect(spy).toHaveBeenCalled(); - expect(isPlaying).toBe(true); - - spy.mockRestore(); -}); -``` - -### `jest.spyOn(object, methodName, accessType?)` - -Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of `accessType` that can be either `'get'` or `'set'`, which proves to be useful when you want to spy on a getter or a setter, respectively. - -Example: - -```js -const video = { - // it's a getter! - get play() { - return true; - }, -}; - -module.exports = video; - -const audio = { - _volume: false, - // it's a setter! - set volume(value) { - this._volume = value; - }, - get volume() { - return this._volume; - }, -}; - -module.exports = audio; -``` - -Example test: - -```js -const video = require('./video'); - -test('plays video', () => { - const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get' - const isPlaying = video.play; - - expect(spy).toHaveBeenCalled(); - expect(isPlaying).toBe(true); - - spy.mockRestore(); -}); - -const audio = require('./audio'); - -test('plays audio', () => { - const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set' - audio.volume = 100; - - expect(spy).toHaveBeenCalled(); - expect(audio.volume).toBe(100); - - spy.mockRestore(); -}); -``` - -### `jest.clearAllMocks()` - -Clears the `mock.calls` and `mock.instances` properties of all mocks. Equivalent to calling [`.mockClear()`](MockFunctionAPI.md#mockfnmockclear) on every mocked function. - -Returns the `jest` object for chaining. - -### `jest.resetAllMocks()` - -Resets the state of all mocks. Equivalent to calling [`.mockReset()`](MockFunctionAPI.md#mockfnmockreset) on every mocked function. - -Returns the `jest` object for chaining. - -### `jest.restoreAllMocks()` - -Restores all mocks back to their original value. Equivalent to calling [`.mockRestore()`](MockFunctionAPI.md#mockfnmockrestore) on every mocked function. Beware that `jest.restoreAllMocks()` only works when the mock was created with `jest.spyOn`; other mocks will require you to manually restore them. - -## Mock timers - -### `jest.useFakeTimers()` - -Instructs Jest to use fake versions of the standard timer functions (`setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `nextTick`, `setImmediate` and `clearImmediate`). - -Returns the `jest` object for chaining. - -### `jest.useRealTimers()` - -Instructs Jest to use the real versions of the standard timer functions. - -Returns the `jest` object for chaining. - -### `jest.runAllTicks()` - -Exhausts the **micro**-task queue (usually interfaced in node via `process.nextTick`). - -When this API is called, all pending micro-tasks that have been queued via `process.nextTick` will be executed. Additionally, if those micro-tasks themselves schedule new micro-tasks, those will be continually exhausted until there are no more micro-tasks remaining in the queue. - -### `jest.runAllTimers()` - -Exhausts both the **macro**-task queue (i.e., all tasks queued by `setTimeout()`, `setInterval()`, and `setImmediate()`) and the **micro**-task queue (usually interfaced in node via `process.nextTick`). - -When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue. - -This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the `setTimeout()` or `setInterval()` callbacks executed. See the [Timer mocks](TimerMocks.md) doc for more information. - -### `jest.runAllImmediates()` - -Exhausts all tasks queued by `setImmediate()`. - -### `jest.advanceTimersByTime(msToRun)` - -##### renamed in Jest **22.0.0+** - -Also under the alias: `.runTimersToTime()` - -Executes only the macro task queue (i.e. all tasks queued by `setTimeout()` or `setInterval()` and `setImmediate()`). - -When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via `setTimeout()` or `setInterval()`, and would be executed within this time frame will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within `msToRun` milliseconds. - -### `jest.runOnlyPendingTimers()` - -Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by `setTimeout()` or `setInterval()` up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. - -This is useful for scenarios such as one where the module being tested schedules a `setTimeout()` whose callback schedules another `setTimeout()` recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time. - -### `jest.advanceTimersToNextTimer(steps)` - -Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run. - -Optionally, you can provide `steps`, so it will run `steps` amount of next timeouts/intervals. - -### `jest.clearAllTimers()` - -Removes any pending timers from the timer system. - -This means, if any timers have been scheduled (but have not yet executed), they will be cleared and will never have the opportunity to execute in the future. - -### `jest.getTimerCount()` - -Returns the number of fake timers still left to run. - -## Misc - -### `jest.setTimeout(timeout)` - -Set the default timeout interval for tests and before/after hooks in milliseconds. This only affects the test file from which this function is called. - -_Note: The default timeout interval is 5 seconds if this method is not called._ - -_Note: If you want to set the timeout for all test files, a good place to do this is in `setupFilesAfterEnv`._ - -Example: - -```js -jest.setTimeout(1000); // 1 second -``` - -### `jest.retryTimes()` - -Runs failed tests n-times until they pass or until the max number of retries is exhausted. This only works with [jest-circus](https://github.com/facebook/jest/tree/master/packages/jest-circus)! - -Example in a test: - -```js -jest.retryTimes(3); -test('will fail', () => { - expect(true).toBe(false); -}); -``` - -Returns the `jest` object for chaining. diff --git a/website/versioned_docs/version-25.3/CLI.md b/website/versioned_docs/version-25.x/CLI.md similarity index 99% rename from website/versioned_docs/version-25.3/CLI.md rename to website/versioned_docs/version-25.x/CLI.md index a28fafb6d30f..3194db9e7236 100644 --- a/website/versioned_docs/version-25.3/CLI.md +++ b/website/versioned_docs/version-25.x/CLI.md @@ -1,5 +1,5 @@ --- -id: version-25.3-cli +id: version-25.x-cli title: Jest CLI Options original_id: cli --- diff --git a/website/versioned_docs/version-25.5/Configuration.md b/website/versioned_docs/version-25.x/Configuration.md similarity index 99% rename from website/versioned_docs/version-25.5/Configuration.md rename to website/versioned_docs/version-25.x/Configuration.md index afb34e1c20bf..f1282e6fa45f 100644 --- a/website/versioned_docs/version-25.5/Configuration.md +++ b/website/versioned_docs/version-25.x/Configuration.md @@ -1,5 +1,5 @@ --- -id: version-25.5-configuration +id: version-25.x-configuration title: Configuring Jest original_id: configuration --- diff --git a/website/versioned_docs/version-25.5/Es6ClassMocks.md b/website/versioned_docs/version-25.x/Es6ClassMocks.md similarity index 99% rename from website/versioned_docs/version-25.5/Es6ClassMocks.md rename to website/versioned_docs/version-25.x/Es6ClassMocks.md index f84c438025f4..a6bf0a09f9b2 100644 --- a/website/versioned_docs/version-25.5/Es6ClassMocks.md +++ b/website/versioned_docs/version-25.x/Es6ClassMocks.md @@ -1,5 +1,5 @@ --- -id: version-25.5-es6-class-mocks +id: version-25.x-es6-class-mocks title: ES6 Class Mocks original_id: es6-class-mocks --- diff --git a/website/versioned_docs/version-25.1/ExpectAPI.md b/website/versioned_docs/version-25.x/ExpectAPI.md similarity index 99% rename from website/versioned_docs/version-25.1/ExpectAPI.md rename to website/versioned_docs/version-25.x/ExpectAPI.md index 4c30f69ac38b..f3163da25bc0 100644 --- a/website/versioned_docs/version-25.1/ExpectAPI.md +++ b/website/versioned_docs/version-25.x/ExpectAPI.md @@ -1,5 +1,5 @@ --- -id: version-25.1-expect +id: version-25.x-expect title: Expect original_id: expect --- diff --git a/website/versioned_docs/version-25.5/GlobalAPI.md b/website/versioned_docs/version-25.x/GlobalAPI.md similarity index 99% rename from website/versioned_docs/version-25.5/GlobalAPI.md rename to website/versioned_docs/version-25.x/GlobalAPI.md index 872aa7c6fa5d..a19799f80898 100644 --- a/website/versioned_docs/version-25.5/GlobalAPI.md +++ b/website/versioned_docs/version-25.x/GlobalAPI.md @@ -1,5 +1,5 @@ --- -id: version-25.5-api +id: version-25.x-api title: Globals original_id: api --- diff --git a/website/versioned_docs/version-25.5/JestObjectAPI.md b/website/versioned_docs/version-25.x/JestObjectAPI.md similarity index 99% rename from website/versioned_docs/version-25.5/JestObjectAPI.md rename to website/versioned_docs/version-25.x/JestObjectAPI.md index 04f2414db41a..a4a19efdc61a 100644 --- a/website/versioned_docs/version-25.5/JestObjectAPI.md +++ b/website/versioned_docs/version-25.x/JestObjectAPI.md @@ -1,5 +1,5 @@ --- -id: version-25.5-jest-object +id: version-25.x-jest-object title: The Jest Object original_id: jest-object --- diff --git a/website/versioned_docs/version-25.1/JestPlatform.md b/website/versioned_docs/version-25.x/JestPlatform.md similarity index 93% rename from website/versioned_docs/version-25.1/JestPlatform.md rename to website/versioned_docs/version-25.x/JestPlatform.md index 4c71970c982f..178945aeffeb 100644 --- a/website/versioned_docs/version-25.1/JestPlatform.md +++ b/website/versioned_docs/version-25.x/JestPlatform.md @@ -1,5 +1,5 @@ --- -id: version-25.1-jest-platform +id: version-25.x-jest-platform title: Jest Platform original_id: jest-platform --- @@ -59,7 +59,7 @@ const code = ` * * @flow */ - + console.log('Hello World!'); `; @@ -120,7 +120,7 @@ You can read more about `jest-validate` in the [readme file](https://github.com/ ## jest-worker -Module used for parallelization of tasks. Exports a class `Worker` that takes the path of Node.js module and lets you call the module's exported methods as if they were class methods, returning a promise that resolves when the specified method finishes its execution in a forked process. +Module used for parallelization of tasks. Exports a class `JestWorker` that takes the path of Node.js module and lets you call the module's exported methods as if they were class methods, returning a promise that resolves when the specified method finishes its execution in a forked process. ### Example diff --git a/website/versioned_docs/version-25.1/MockFunctions.md b/website/versioned_docs/version-25.x/MockFunctions.md similarity index 99% rename from website/versioned_docs/version-25.1/MockFunctions.md rename to website/versioned_docs/version-25.x/MockFunctions.md index f9ada1561dba..39d2282142e1 100644 --- a/website/versioned_docs/version-25.1/MockFunctions.md +++ b/website/versioned_docs/version-25.x/MockFunctions.md @@ -1,5 +1,5 @@ --- -id: version-25.1-mock-functions +id: version-25.x-mock-functions title: Mock Functions original_id: mock-functions --- diff --git a/website/versioned_docs/version-25.3/TestingAsyncCode.md b/website/versioned_docs/version-25.x/TestingAsyncCode.md similarity index 99% rename from website/versioned_docs/version-25.3/TestingAsyncCode.md rename to website/versioned_docs/version-25.x/TestingAsyncCode.md index 5d1048c83ccd..3d8487c805d4 100644 --- a/website/versioned_docs/version-25.3/TestingAsyncCode.md +++ b/website/versioned_docs/version-25.x/TestingAsyncCode.md @@ -1,5 +1,5 @@ --- -id: version-25.3-asynchronous +id: version-25.x-asynchronous title: Testing Asynchronous Code original_id: asynchronous --- diff --git a/website/versioned_docs/version-25.1/TestingFrameworks.md b/website/versioned_docs/version-25.x/TestingFrameworks.md similarity index 98% rename from website/versioned_docs/version-25.1/TestingFrameworks.md rename to website/versioned_docs/version-25.x/TestingFrameworks.md index 030b07fb927d..65a0b6c20be0 100644 --- a/website/versioned_docs/version-25.1/TestingFrameworks.md +++ b/website/versioned_docs/version-25.x/TestingFrameworks.md @@ -1,5 +1,5 @@ --- -id: version-25.1-testing-frameworks +id: version-25.x-testing-frameworks title: Testing Web Frameworks original_id: testing-frameworks --- diff --git a/website/versioned_docs/version-25.1/Troubleshooting.md b/website/versioned_docs/version-25.x/Troubleshooting.md similarity index 99% rename from website/versioned_docs/version-25.1/Troubleshooting.md rename to website/versioned_docs/version-25.x/Troubleshooting.md index 1e9aa2cdf87c..1fe2499394b4 100644 --- a/website/versioned_docs/version-25.1/Troubleshooting.md +++ b/website/versioned_docs/version-25.x/Troubleshooting.md @@ -1,5 +1,5 @@ --- -id: version-25.1-troubleshooting +id: version-25.x-troubleshooting title: Troubleshooting original_id: troubleshooting --- diff --git a/website/versioned_docs/version-25.1/TutorialAsync.md b/website/versioned_docs/version-25.x/TutorialAsync.md similarity index 99% rename from website/versioned_docs/version-25.1/TutorialAsync.md rename to website/versioned_docs/version-25.x/TutorialAsync.md index 07937b7b5281..887e8423e118 100644 --- a/website/versioned_docs/version-25.1/TutorialAsync.md +++ b/website/versioned_docs/version-25.x/TutorialAsync.md @@ -1,5 +1,5 @@ --- -id: version-25.1-tutorial-async +id: version-25.x-tutorial-async title: An Async Example original_id: tutorial-async --- diff --git a/website/versioned_docs/version-25.3/TutorialReact.md b/website/versioned_docs/version-25.x/TutorialReact.md similarity index 99% rename from website/versioned_docs/version-25.3/TutorialReact.md rename to website/versioned_docs/version-25.x/TutorialReact.md index 3534b51d5a03..e671f8e21bb3 100644 --- a/website/versioned_docs/version-25.3/TutorialReact.md +++ b/website/versioned_docs/version-25.x/TutorialReact.md @@ -1,5 +1,5 @@ --- -id: version-25.3-tutorial-react +id: version-25.x-tutorial-react title: Testing React Apps original_id: tutorial-react --- diff --git a/website/versioned_docs/version-25.3/TutorialReactNative.md b/website/versioned_docs/version-25.x/TutorialReactNative.md similarity index 99% rename from website/versioned_docs/version-25.3/TutorialReactNative.md rename to website/versioned_docs/version-25.x/TutorialReactNative.md index 0d2597d8c35a..4641502e339e 100644 --- a/website/versioned_docs/version-25.3/TutorialReactNative.md +++ b/website/versioned_docs/version-25.x/TutorialReactNative.md @@ -1,5 +1,5 @@ --- -id: version-25.3-tutorial-react-native +id: version-25.x-tutorial-react-native title: Testing React Native Apps original_id: tutorial-react-native --- diff --git a/website/versioned_docs/version-25.1/CLI.md b/website/versioned_docs/version-26.0/CLI.md similarity index 93% rename from website/versioned_docs/version-25.1/CLI.md rename to website/versioned_docs/version-26.0/CLI.md index 731f4b81b1f2..ce5c4fcaac88 100644 --- a/website/versioned_docs/version-25.1/CLI.md +++ b/website/versioned_docs/version-26.0/CLI.md @@ -1,5 +1,5 @@ --- -id: version-25.1-cli +id: version-26.0-cli title: Jest CLI Options original_id: cli --- @@ -157,11 +157,7 @@ Alias: `--collectCoverage`. Indicates that test coverage information should be c 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 and comes with a few caveats - -1. Your node version must include `vm.compileFunction`, which was introduced in [node 10.10](https://nodejs.org/dist/latest-v12.x/docs/api/vm.html#vm_vm_compilefunction_code_params_options) -1. Tests needs to run in Node test environment (support for `jsdom` requires [`jest-environment-jsdom-sixteen`](https://www.npmjs.com/package/jest-environment-jsdom-sixteen)) -1. V8 has way better data in the later versions, so using the latest versions of node (v13 at the time of this writing) will yield better results +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` @@ -237,8 +233,6 @@ Disables stack trace in test results output. Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing. -**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 - ### `--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). diff --git a/website/versioned_docs/version-25.3/Configuration.md b/website/versioned_docs/version-26.0/Configuration.md similarity index 97% rename from website/versioned_docs/version-25.3/Configuration.md rename to website/versioned_docs/version-26.0/Configuration.md index 3c2a23692126..23d6da577d3d 100644 --- a/website/versioned_docs/version-25.3/Configuration.md +++ b/website/versioned_docs/version-26.0/Configuration.md @@ -1,5 +1,5 @@ --- -id: version-25.3-configuration +id: version-26.0-configuration title: Configuring Jest original_id: configuration --- @@ -106,12 +106,6 @@ 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`. -### `browser` [boolean] - -Default: `false` - -Respect Browserify's [`"browser"` field](https://github.com/substack/browserify-handbook#browser-field) in `package.json` when resolving modules. Some modules export different versions based on whether they are operating in Node or a browser. - ### `cacheDirectory` [string] Default: `"/tmp/"` @@ -190,11 +184,7 @@ These pattern strings match against the full path. Use the `` string to 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 and comes with a few caveats - -1. Your node version must include `vm.compileFunction`, which was introduced in [node 10.10](https://nodejs.org/dist/latest-v12.x/docs/api/vm.html#vm_vm_compilefunction_code_params_options) -1. Tests needs to run in Node test environment (support for `jsdom` requires [`jest-environment-jsdom-sixteen`](https://www.npmjs.com/package/jest-environment-jsdom-sixteen)) -1. V8 has way better data in the later versions, so using the latest versions of node (v13 at the time of this writing) will yield better results +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\] @@ -690,7 +680,6 @@ This option allows the use of a custom resolver. This resolver must be a node mo ```json { "basedir": string, - "browser": bool, "defaultResolver": "function(request, options)", "extensions": [string], "moduleDirectory": [string], @@ -701,7 +690,18 @@ This option allows the use of a custom resolver. This resolver must be a node mo The function should either return a path to the module that should be resolved or throw an error if the module can't be found. -Note: the defaultResolver passed as options is the jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom one, e.g. (request, options). +Note: the defaultResolver passed as options is the Jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom one, e.g. `(request, options)`. + +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" + } +} +``` ### `restoreMocks` [boolean] @@ -880,7 +880,7 @@ Pretty foo: Object { 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#serialize). +More about serializers API can be found [here](https://github.com/facebook/jest/tree/master/packages/pretty-format/README.md#serialize). ### `testEnvironment` [string] diff --git a/website/versioned_docs/version-25.5/JestPlatform.md b/website/versioned_docs/version-26.0/JestPlatform.md similarity index 99% rename from website/versioned_docs/version-25.5/JestPlatform.md rename to website/versioned_docs/version-26.0/JestPlatform.md index 1b2ddf710cd2..a35a2a4b6dcc 100644 --- a/website/versioned_docs/version-25.5/JestPlatform.md +++ b/website/versioned_docs/version-26.0/JestPlatform.md @@ -1,5 +1,5 @@ --- -id: version-25.5-jest-platform +id: version-26.0-jest-platform title: Jest Platform original_id: jest-platform --- diff --git a/website/versions.json b/website/versions.json index 359fa3ec8a76..1b6301798894 100644 --- a/website/versions.json +++ b/website/versions.json @@ -1,7 +1,6 @@ [ - "25.5", - "25.3", - "25.1", + "26.0", + "25.x", "24.x", "23.x", "22.x"