From d425a49bd575e7167bc786f3c4f2833589091fa1 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Tue, 28 Apr 2020 21:47:32 +0200 Subject: [PATCH] chore: roll new version of docs --- CHANGELOG.md | 2 +- .../version-25.5/Configuration.md | 1210 +++++++++++++++++ .../version-25.5/Es6ClassMocks.md | 364 +++++ .../versioned_docs/version-25.5/GlobalAPI.md | 676 +++++++++ .../version-25.5/JestObjectAPI.md | 672 +++++++++ .../version-25.5/JestPlatform.md | 175 +++ website/versions.json | 1 + 7 files changed, 3099 insertions(+), 1 deletion(-) create mode 100644 website/versioned_docs/version-25.5/Configuration.md create mode 100644 website/versioned_docs/version-25.5/Es6ClassMocks.md create mode 100644 website/versioned_docs/version-25.5/GlobalAPI.md create mode 100644 website/versioned_docs/version-25.5/JestObjectAPI.md create mode 100644 website/versioned_docs/version-25.5/JestPlatform.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 982052fb09c1..a2aaef5db739 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ ### Performance -## 24.5.0 +## 25.5.0 ### Features diff --git a/website/versioned_docs/version-25.5/Configuration.md b/website/versioned_docs/version-25.5/Configuration.md new file mode 100644 index 000000000000..69e68bae0396 --- /dev/null +++ b/website/versioned_docs/version-25.5/Configuration.md @@ -0,0 +1,1210 @@ +--- +id: version-25.5-configuration +title: Configuring Jest +original_id: configuration +--- + +Jest's configuration can be defined in the `package.json` file of your project, or through a `jest.config.js` file or through the `--config ` option. If you'd like to use your `package.json` to store Jest's config, the `"jest"` key should be used on the top level so Jest will know how to find your settings: + +```json +{ + "name": "my-project", + "jest": { + "verbose": true + } +} +``` + +Or through JavaScript: + +```js +// jest.config.js +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._ + +_Note: You can pass additional options to the istanbul reporter using the tuple form. For example:_ + +```json +["json", ["lcov", {"projectRoot": "../../"}]] +``` + +### `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 or to arrays of module names that allow to stub out resources, like images or styles with a single module. + +Modules that are mapped to an alias are unmocked by default, regardless of whether automocking is enabled or not. + +Use `` string token to refer to [`rootDir`](#rootdir-string) value if you want to use file paths. + +Additionally, you can substitute captured regex groups using numbered backreferences. + +Example: + +```json +{ + "moduleNameMapper": { + "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub", + "^[./a-zA-Z0-9$_-]+\\.png$": "/RelativeImageStub.js", + "module_name_(.*)": "/substituted_module_$1.js", + "assets/(.*)": [ + "/images/$1", + "/photos/$1", + "/recipes/$1" + ] + } +} +``` + +The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. This is true for arrays of module names as well. + +_Note: If you provide module name without boundaries `^$` it may cause hard to spot errors. E.g. `relay` will replace all modules which contain `relay` as a substring in its name: `relay`, `react-relay` and `graphql-relay` will all be pointed to your stub._ + +### `modulePathIgnorePatterns` [array\] + +Default: `[]` + +An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be `require()`-able in the test environment. + +These pattern strings match against the full path. Use the `` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `["/build/"]`. + +### `modulePaths` [array\] + +Default: `[]` + +An alternative API to setting the `NODE_PATH` env variable, `modulePaths` is an array of absolute paths to additional locations to search when resolving modules. Use the `` string token to include the path to your project's root directory. Example: `["/app/"]`. + +### `notify` [boolean] + +Default: `false` + +Activates notifications for test results. + +**Beware:** Jest uses [node-notifier](https://github.com/mikaelbr/node-notifier) to display desktop notifications. On Windows, it creates a new start menu entry on the first use and not display the notification. Notifications will be properly displayed on subsequent runs + +### `notifyMode` [string] + +Default: `failure-change` + +Specifies notification mode. Requires `notify: true`. + +#### Modes + +- `always`: always send a notification. +- `failure`: send a notification when tests fail. +- `success`: send a notification when tests pass. +- `change`: send a notification when the status changed. +- `success-change`: send a notification when tests pass or once when it fails. +- `failure-change`: send a notification when tests fail or once when it passes. + +### `preset` [string] + +Default: `undefined` + +A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a `jest-preset.json` or `jest-preset.js` file at the root. + +For example, this preset `foo-bar/jest-preset.js` will be configured as follows: + +```json +{ + "preset": "foo-bar" +} +``` + +Presets may also be relative 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 than being executed in parallel your class should have the property `isSerial` to be set as `true`. + +### `setupFiles` [array] + +Default: `[]` + +A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself. + +It's also worth noting that `setupFiles` will execute _before_ [`setupFilesAfterEnv`](#setupfilesafterenv-array). + +### `setupFilesAfterEnv` [array] + +Default: `[]` + +A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed. Since [`setupFiles`](#setupfiles-array) executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment. + +If you want a path to be [relative to the root directory of your project](#rootdir-string), please include `` inside a path's string, like `"/a-configs-folder"`. + +For example, Jest ships with several plug-ins to `jasmine` that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in these modules. + +_Note: `setupTestFrameworkScriptFile` is deprecated in favor of `setupFilesAfterEnv`._ + +Example `setupFilesAfterEnv` array in a jest.config.js: + +```js +module.exports = { + setupFilesAfterEnv: ['./jest.setup.js'], +}; +``` + +Example `jest.setup.js` file + +```js +jest.setTimeout(10000); // in milliseconds +``` + +### `snapshotResolver` [string] + +Default: `undefined` + +The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk. + +Example snapshot resolver module: + +```js +module.exports = { + // resolves from test to snapshot path + resolveSnapshotPath: (testPath, snapshotExtension) => + testPath.replace('__tests__', '__snapshots__') + snapshotExtension, + + // resolves from snapshot to test path + resolveTestPath: (snapshotFilePath, snapshotExtension) => + snapshotFilePath + .replace('__snapshots__', '__tests__') + .slice(0, -snapshotExtension.length), + + // Example test path, used for preflight consistency check of the implementation above + testPathForConsistencyCheck: 'some/__tests__/example.test.js', +}; +``` + +### `snapshotSerializers` [array\] + +Default: `[]` + +A list of paths to snapshot serializer modules Jest should use for snapshot testing. + +Jest has default serializers for built-in JavaScript types, HTML elements (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) and for React elements. See [snapshot test tutorial](TutorialReactNative.md#snapshot-test) for more information. + +Example serializer module: + +```js +// my-serializer-module +module.exports = { + serialize(val, config, indentation, depth, refs, printer) { + return 'Pretty foo: ' + printer(val.foo); + }, + + test(val) { + return val && val.hasOwnProperty('foo'); + }, +}; +``` + +`printer` is a function that serializes a value using existing plugins. + +To use `my-serializer-module` as a serializer, configuration would be as follows: + +```json +{ + ... + "jest": { + "snapshotSerializers": ["my-serializer-module"] + } +} +``` + +Finally tests would look as follows: + +```js +test(() => { + const bar = { + foo: { + x: 1, + y: 2, + }, + }; + + expect(bar).toMatchSnapshot(); +}); +``` + +Rendered snapshot: + +```json +Pretty foo: Object { + "x": 1, + "y": 2, +} +``` + +To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. + +More about serializers API can be found [here](https://github.com/facebook/jest/tree/master/packages/pretty-format/README.md#serialize). + +### `testEnvironment` [string] + +Default: `"jsdom"` + +The test environment that will be used for testing. The default environment in Jest is a browser-like environment through [jsdom](https://github.com/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 an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/master/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/master/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. + +Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with it's value set to an empty string. If the pragma is not present, it will not be present in the object. + +_Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment._ + +Example: + +```js +// my-custom-environment +const NodeEnvironment = require('jest-environment-node'); + +class CustomEnvironment extends NodeEnvironment { + constructor(config, context) { + super(config, context); + this.testPath = context.testPath; + this.docblockPragmas = context.docblockPragmas; + } + + async setup() { + await super.setup(); + await someSetupTasks(this.testPath); + this.global.someGlobalObject = createGlobalObject(); + + // Will trigger if docblock contains @my-custom-pragma my-pragma-value + if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') { + // ... + } + } + + async teardown() { + this.global.someGlobalObject = destroyGlobalObject(); + await someTeardownTasks(); + await super.teardown(); + } + + runScript(script) { + return super.runScript(script); + } + + async handleTestEvent(event, state) { + if (event.name === 'test_start') { + // ... + } + } +} + +module.exports = CustomEnvironment; +``` + +```js +// my-test-suite +let someGlobalObject; + +beforeAll(() => { + someGlobalObject = global.someGlobalObject; +}); +``` + +### `testEnvironmentOptions` [Object] + +Default: `{}` + +Test environment options that will be passed to the `testEnvironment`. The relevant options depend on the environment. For example you can override options given to [jsdom](https://github.com/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: `undefined` + +A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that isn't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](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: if you are using the `babel-jest` transformer and want to use an additional code preprocessor, keep in mind that when "transform" is overwritten in any way the `babel-jest` is not loaded automatically anymore. If you want to use it to compile JavaScript code it has to be explicitly defined. See [babel-jest plugin](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.5/Es6ClassMocks.md b/website/versioned_docs/version-25.5/Es6ClassMocks.md new file mode 100644 index 000000000000..f84c438025f4 --- /dev/null +++ b/website/versioned_docs/version-25.5/Es6ClassMocks.md @@ -0,0 +1,364 @@ +--- +id: version-25.5-es6-class-mocks +title: ES6 Class Mocks +original_id: es6-class-mocks +--- + +Jest can be used to mock ES6 classes that are imported into files you want to test. + +ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using [mock functions](MockFunctions.md). + +## An ES6 Class Example + +We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. + +```javascript +// sound-player.js +export default class SoundPlayer { + constructor() { + this.foo = 'bar'; + } + + playSoundFile(fileName) { + console.log('Playing sound file ' + fileName); + } +} +``` + +```javascript +// sound-player-consumer.js +import SoundPlayer from './sound-player'; + +export default class SoundPlayerConsumer { + constructor() { + this.soundPlayer = new SoundPlayer(); + } + + playSomethingCool() { + const coolSoundFileName = 'song.mp3'; + this.soundPlayer.playSoundFile(coolSoundFileName); + } +} +``` + +## The 4 ways to create an ES6 class mock + +### Automatic mock + +Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with [mock functions](MockFunctions.md) that always return `undefined`. Method calls are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. + +Please note that if you use arrow functions in your classes, they will _not_ be part of the mock. The reason for that is that arrow functions are not present on the object's prototype, they are merely properties holding a reference to a function. + +If you don't need to replace the implementation of the class, this is the easiest option to set up. For example: + +```javascript +import SoundPlayer from './sound-player'; +import SoundPlayerConsumer from './sound-player-consumer'; +jest.mock('./sound-player'); // SoundPlayer is now a mock constructor + +beforeEach(() => { + // Clear all instances and calls to constructor and all methods: + SoundPlayer.mockClear(); +}); + +it('We can check if the consumer called the class constructor', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + expect(SoundPlayer).toHaveBeenCalledTimes(1); +}); + +it('We can check if the consumer called a method on the class instance', () => { + // Show that mockClear() is working: + expect(SoundPlayer).not.toHaveBeenCalled(); + + const soundPlayerConsumer = new SoundPlayerConsumer(); + // Constructor should have been called again: + expect(SoundPlayer).toHaveBeenCalledTimes(1); + + const coolSoundFileName = 'song.mp3'; + soundPlayerConsumer.playSomethingCool(); + + // mock.instances is available with automatic mocks: + const mockSoundPlayerInstance = SoundPlayer.mock.instances[0]; + const mockPlaySoundFile = mockSoundPlayerInstance.playSoundFile; + expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName); + // Equivalent to above check: + expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName); + expect(mockPlaySoundFile).toHaveBeenCalledTimes(1); +}); +``` + +### Manual mock + +Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. + +```javascript +// __mocks__/sound-player.js + +// Import this named export into your test file: +export const mockPlaySoundFile = jest.fn(); +const mock = jest.fn().mockImplementation(() => { + return {playSoundFile: mockPlaySoundFile}; +}); + +export default mock; +``` + +Import the mock and the mock method shared by all instances: + +```javascript +// sound-player-consumer.test.js +import SoundPlayer, {mockPlaySoundFile} from './sound-player'; +import SoundPlayerConsumer from './sound-player-consumer'; +jest.mock('./sound-player'); // SoundPlayer is now a mock constructor + +beforeEach(() => { + // Clear all instances and calls to constructor and all methods: + SoundPlayer.mockClear(); + mockPlaySoundFile.mockClear(); +}); + +it('We can check if the consumer called the class constructor', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + expect(SoundPlayer).toHaveBeenCalledTimes(1); +}); + +it('We can check if the consumer called a method on the class instance', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + const coolSoundFileName = 'song.mp3'; + soundPlayerConsumer.playSomethingCool(); + expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName); +}); +``` + +### Calling [`jest.mock()`](JestObjectAPI.md#jestmockmodulename-factory-options) with the module factory parameter + +`jest.mock(path, moduleFactory)` takes a **module factory** argument. A module factory is a function that returns the mock. + +In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). + +```javascript +import SoundPlayer from './sound-player'; +const mockPlaySoundFile = jest.fn(); +jest.mock('./sound-player', () => { + return jest.fn().mockImplementation(() => { + return {playSoundFile: mockPlaySoundFile}; + }); +}); +``` + +A limitation with the factory parameter is that, since calls to `jest.mock()` are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'. It's up to you to guarantee that they will be initialized on time! For example, the following will throw an out-of-scope error due to the use of 'fake' instead of 'mock' in the variable declaration: + +```javascript +// Note: this will fail +import SoundPlayer from './sound-player'; +const fakePlaySoundFile = jest.fn(); +jest.mock('./sound-player', () => { + return jest.fn().mockImplementation(() => { + return {playSoundFile: fakePlaySoundFile}; + }); +}); +``` + +### Replacing the mock using [`mockImplementation()`](MockFunctionAPI.md#mockfnmockimplementationfn) or [`mockImplementationOnce()`](MockFunctionAPI.md#mockfnmockimplementationoncefn) + +You can replace all of the above mocks in order to change the implementation, for a single test or all tests, by calling `mockImplementation()` on the existing mock. + +Calls to jest.mock are hoisted to the top of the code. You can specify a mock later, e.g. in `beforeAll()`, by calling `mockImplementation()` (or `mockImplementationOnce()`) on the existing mock instead of using the factory parameter. This also allows you to change the mock between tests, if needed: + +```javascript +import SoundPlayer from './sound-player'; +import SoundPlayerConsumer from './sound-player-consumer'; + +jest.mock('./sound-player'); + +describe('When SoundPlayer throws an error', () => { + beforeAll(() => { + SoundPlayer.mockImplementation(() => { + return { + playSoundFile: () => { + throw new Error('Test error'); + }, + }; + }); + }); + + it('Should throw an error when calling playSomethingCool', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + expect(() => soundPlayerConsumer.playSomethingCool()).toThrow(); + }); +}); +``` + +## In depth: Understanding mock constructor functions + +Building your constructor function mock using `jest.fn().mockImplementation()` makes mocks appear more complicated than they really are. This section shows how you can create your own mocks to illustrate how mocking works. + +### Manual mock that is another ES6 class + +If you define an ES6 class using the same filename as the mocked class in the `__mocks__` folder, it will serve as the mock. This class will be used in place of the real class. This allows you to inject a test implementation for the class, but does not provide a way to spy on calls. + +For the contrived example, the mock might look like this: + +```javascript +// __mocks__/sound-player.js +export default class SoundPlayer { + constructor() { + console.log('Mock SoundPlayer: constructor was called'); + } + + playSoundFile() { + console.log('Mock SoundPlayer: playSoundFile was called'); + } +} +``` + +### Mock using module factory parameter + +The module factory function passed to `jest.mock(path, moduleFactory)` can be a HOF that returns a function\*. This will allow calling `new` on the mock. Again, this allows you to inject different behavior for testing, but does not provide a way to spy on calls. + +#### \* Module factory function must return a function + +In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). + +```javascript +jest.mock('./sound-player', () => { + return function () { + return {playSoundFile: () => {}}; + }; +}); +``` + +**_Note: Arrow functions won't work_** + +Note that the mock can't be an arrow function because calling `new` on an arrow function is not allowed in JavaScript. So this won't work: + +```javascript +jest.mock('./sound-player', () => { + return () => { + // Does not work; arrow functions can't be called with new + return {playSoundFile: () => {}}; + }; +}); +``` + +This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, unless the code is transpiled to ES5, e.g. by `@babel/preset-env`. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.) + +## Keeping track of usage (spying on the mock) + +Injecting a test implementation is helpful, but you will probably also want to test whether the class constructor and methods are called with the correct parameters. + +### Spying on the constructor + +In order to track calls to the constructor, replace the function returned by the HOF with a Jest mock function. Create it with [`jest.fn()`](JestObjectAPI.md#jestfnimplementation), and then specify its implementation with `mockImplementation()`. + +```javascript +import SoundPlayer from './sound-player'; +jest.mock('./sound-player', () => { + // Works and lets you check for constructor calls: + return jest.fn().mockImplementation(() => { + return {playSoundFile: () => {}}; + }); +}); +``` + +This will let us inspect usage of our mocked class, using `SoundPlayer.mock.calls`: `expect(SoundPlayer).toHaveBeenCalled();` or near-equivalent: `expect(SoundPlayer.mock.calls.length).toEqual(1);` + +### Mocking non default class exports + +If the class is **not** the default export from the module then you need to return an object with the key that is the same as the class export name. + +```javascript +import {SoundPlayer} from './sound-player'; +jest.mock('./sound-player', () => { + // Works and lets you check for constructor calls: + return { + SoundPlayer: jest.fn().mockImplementation(() => { + return {playSoundFile: () => {}}; + }), + }; +}); +``` + +### Spying on methods of our class + +Our mocked class will need to provide any member functions (`playSoundFile` in the example) that will be called during our tests, or else we'll get an error for calling a function that doesn't exist. But we'll probably want to also spy on calls to those methods, to ensure that they were called with the expected parameters. + +A new object will be created each time the mock constructor function is called during tests. To spy on method calls in all of these objects, we populate `playSoundFile` with another mock function, and store a reference to that same mock function in our test file, so it's available during tests. + +```javascript +import SoundPlayer from './sound-player'; +const mockPlaySoundFile = jest.fn(); +jest.mock('./sound-player', () => { + return jest.fn().mockImplementation(() => { + return {playSoundFile: mockPlaySoundFile}; + // Now we can track calls to playSoundFile + }); +}); +``` + +The manual mock equivalent of this would be: + +```javascript +// __mocks__/sound-player.js + +// Import this named export into your test file +export const mockPlaySoundFile = jest.fn(); +const mock = jest.fn().mockImplementation(() => { + return {playSoundFile: mockPlaySoundFile}; +}); + +export default mock; +``` + +Usage is similar to the module factory function, except that you can omit the second argument from `jest.mock()`, and you must import the mocked method into your test file, since it is no longer defined there. Use the original module path for this; don't include `__mocks__`. + +### Cleaning up between tests + +To clear the record of calls to the mock constructor function and its methods, we call [`mockClear()`](MockFunctionAPI.md#mockfnmockclear) in the `beforeEach()` function: + +```javascript +beforeEach(() => { + SoundPlayer.mockClear(); + mockPlaySoundFile.mockClear(); +}); +``` + +## Complete example + +Here's a complete test file which uses the module factory parameter to `jest.mock`: + +```javascript +// sound-player-consumer.test.js +import SoundPlayerConsumer from './sound-player-consumer'; +import SoundPlayer from './sound-player'; + +const mockPlaySoundFile = jest.fn(); +jest.mock('./sound-player', () => { + return jest.fn().mockImplementation(() => { + return {playSoundFile: mockPlaySoundFile}; + }); +}); + +beforeEach(() => { + SoundPlayer.mockClear(); + mockPlaySoundFile.mockClear(); +}); + +it('The consumer should be able to call new() on SoundPlayer', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + // Ensure constructor created the object: + expect(soundPlayerConsumer).toBeTruthy(); +}); + +it('We can check if the consumer called the class constructor', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + expect(SoundPlayer).toHaveBeenCalledTimes(1); +}); + +it('We can check if the consumer called a method on the class instance', () => { + const soundPlayerConsumer = new SoundPlayerConsumer(); + const coolSoundFileName = 'song.mp3'; + soundPlayerConsumer.playSomethingCool(); + expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName); +}); +``` diff --git a/website/versioned_docs/version-25.5/GlobalAPI.md b/website/versioned_docs/version-25.5/GlobalAPI.md new file mode 100644 index 000000000000..872aa7c6fa5d --- /dev/null +++ b/website/versioned_docs/version-25.5/GlobalAPI.md @@ -0,0 +1,676 @@ +--- +id: version-25.5-api +title: Globals +original_id: api +--- + +In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them. However, if you prefer explicit imports, you can do `import {describe, expect, it} from '@jest/globals'`. + +## Methods + + + +--- + +## Reference + +### `afterAll(fn, timeout)` + +Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. + +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ + +This is often useful if you want to clean up some global setup state that is shared across tests. + +For example: + +```js +const globalDatabase = makeGlobalDatabase(); + +function cleanUpDatabase(db) { + db.cleanUp(); +} + +afterAll(() => { + cleanUpDatabase(globalDatabase); +}); + +test('can find things', () => { + return globalDatabase.find('thing', {}, results => { + expect(results.length).toBeGreaterThan(0); + }); +}); + +test('can insert a thing', () => { + return globalDatabase.insert('thing', makeThing(), response => { + expect(response.success).toBeTruthy(); + }); +}); +``` + +Here the `afterAll` ensures that `cleanUpDatabase` is called after all tests run. + +If `afterAll` is inside a `describe` block, it runs at the end of the describe block. + +If you want to run some cleanup after every test instead of after all tests, use `afterEach` instead. + +### `afterEach(fn, timeout)` + +Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. + +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ + +This is often useful if you want to clean up some temporary state that is created by each test. + +For example: + +```js +const globalDatabase = makeGlobalDatabase(); + +function cleanUpDatabase(db) { + db.cleanUp(); +} + +afterEach(() => { + cleanUpDatabase(globalDatabase); +}); + +test('can find things', () => { + return globalDatabase.find('thing', {}, results => { + expect(results.length).toBeGreaterThan(0); + }); +}); + +test('can insert a thing', () => { + return globalDatabase.insert('thing', makeThing(), response => { + expect(response.success).toBeTruthy(); + }); +}); +``` + +Here the `afterEach` ensures that `cleanUpDatabase` is called after each test runs. + +If `afterEach` is inside a `describe` block, it only runs after the tests that are inside this describe block. + +If you want to run some cleanup just once, after all of the tests run, use `afterAll` instead. + +### `beforeAll(fn, timeout)` + +Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. + +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ + +This is often useful if you want to set up some global state that will be used by many tests. + +For example: + +```js +const globalDatabase = makeGlobalDatabase(); + +beforeAll(() => { + // Clears the database and adds some testing data. + // Jest will wait for this promise to resolve before running tests. + return globalDatabase.clear().then(() => { + return globalDatabase.insert({testData: 'foo'}); + }); +}); + +// Since we only set up the database once in this example, it's important +// that our tests don't modify it. +test('can find things', () => { + return globalDatabase.find('thing', {}, results => { + expect(results.length).toBeGreaterThan(0); + }); +}); +``` + +Here the `beforeAll` ensures that the database is set up before tests run. If setup was synchronous, you could do this without `beforeAll`. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well. + +If `beforeAll` is inside a `describe` block, it runs at the beginning of the describe block. + +If you want to run something before every test instead of before any test runs, use `beforeEach` instead. + +### `beforeEach(fn, timeout)` + +Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. + +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ + +This is often useful if you want to reset some global state that will be used by many tests. + +For example: + +```js +const globalDatabase = makeGlobalDatabase(); + +beforeEach(() => { + // Clears the database and adds some testing data. + // Jest will wait for this promise to resolve before running tests. + return globalDatabase.clear().then(() => { + return globalDatabase.insert({testData: 'foo'}); + }); +}); + +test('can find things', () => { + return globalDatabase.find('thing', {}, results => { + expect(results.length).toBeGreaterThan(0); + }); +}); + +test('can insert a thing', () => { + return globalDatabase.insert('thing', makeThing(), response => { + expect(response.success).toBeTruthy(); + }); +}); +``` + +Here the `beforeEach` ensures that the database is reset for each test. + +If `beforeEach` is inside a `describe` block, it runs for each test in the describe block. + +If you only need to run some setup code once, before any tests run, use `beforeAll` instead. + +### `describe(name, fn)` + +`describe(name, fn)` creates a block that groups together several related tests. For example, if you have a `myBeverage` object that is supposed to be delicious but not sour, you could test it with: + +```js +const myBeverage = { + delicious: true, + sour: false, +}; + +describe('my beverage', () => { + test('is delicious', () => { + expect(myBeverage.delicious).toBeTruthy(); + }); + + test('is not sour', () => { + expect(myBeverage.sour).toBeFalsy(); + }); +}); +``` + +This isn't required - you can write the `test` blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups. + +You can also nest `describe` blocks if you have a hierarchy of tests: + +```js +const binaryStringToNumber = binString => { + if (!/^[01]+$/.test(binString)) { + throw new CustomError('Not a binary number.'); + } + + return parseInt(binString, 2); +}; + +describe('binaryStringToNumber', () => { + describe('given an invalid binary string', () => { + test('composed of non-numbers throws CustomError', () => { + expect(() => binaryStringToNumber('abc')).toThrowError(CustomError); + }); + + test('with extra whitespace throws CustomError', () => { + expect(() => binaryStringToNumber(' 100')).toThrowError(CustomError); + }); + }); + + describe('given a valid binary string', () => { + test('returns the correct number', () => { + expect(binaryStringToNumber('100')).toBe(4); + }); + }); +}); +``` + +### `describe.each(table)(name, fn, timeout)` + +Use `describe.each` if you keep duplicating the same test suites with different data. `describe.each` allows you to write the test suite once and pass data in. + +`describe.each` is available with two APIs: + +#### 1. `describe.each(table)(name, fn, timeout)` + +- `table`: `Array` of Arrays with the arguments that are passed into the `fn` for each row. + - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` +- `name`: `String` the title of the test suite. + - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. +- `fn`: `Function` the suite of tests to be ran, this is the function that will receive the parameters in each row as function arguments. +- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. _Note: The default timeout is 5 seconds._ + +Example: + +```js +describe.each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +])('.add(%i, %i)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test(`returned value not be greater than ${expected}`, () => { + expect(a + b).not.toBeGreaterThan(expected); + }); + + test(`returned value not be less than ${expected}`, () => { + expect(a + b).not.toBeLessThan(expected); + }); +}); +``` + +#### 2. `` describe.each`table`(name, fn, timeout) `` + +- `table`: `Tagged Template Literal` + - First row of variable name column headings separated with `|` + - One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. +- `name`: `String` the title of the test suite, use `$variable` to inject test data into the suite title from the tagged template expressions. + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` +- `fn`: `Function` the suite of tests to be ran, this is the function that will receive the test data object. +- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. _Note: The default timeout is 5 seconds._ + +Example: + +```js +describe.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test(`returned value not be greater than ${expected}`, () => { + expect(a + b).not.toBeGreaterThan(expected); + }); + + test(`returned value not be less than ${expected}`, () => { + expect(a + b).not.toBeLessThan(expected); + }); +}); +``` + +### `describe.only(name, fn)` + +Also under the alias: `fdescribe(name, fn)` + +You can use `describe.only` if you want to run only one describe block: + +```js +describe.only('my beverage', () => { + test('is delicious', () => { + expect(myBeverage.delicious).toBeTruthy(); + }); + + test('is not sour', () => { + expect(myBeverage.sour).toBeFalsy(); + }); +}); + +describe('my other beverage', () => { + // ... will be skipped +}); +``` + +### `describe.only.each(table)(name, fn)` + +Also under the aliases: `fdescribe.each(table)(name, fn)` and `` fdescribe.each`table`(name, fn) `` + +Use `describe.only.each` if you want to only run specific tests suites of data driven tests. + +`describe.only.each` is available with two APIs: + +#### `describe.only.each(table)(name, fn)` + +```js +describe.only.each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +])('.add(%i, %i)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); + +test('will not be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +#### `` describe.only.each`table`(name, fn) `` + +```js +describe.only.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`('returns $expected when $a is added $b', ({a, b, expected}) => { + test('passes', () => { + expect(a + b).toBe(expected); + }); +}); + +test('will not be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +### `describe.skip(name, fn)` + +Also under the alias: `xdescribe(name, fn)` + +You can use `describe.skip` if you do not want to run a particular describe block: + +```js +describe('my beverage', () => { + test('is delicious', () => { + expect(myBeverage.delicious).toBeTruthy(); + }); + + test('is not sour', () => { + expect(myBeverage.sour).toBeFalsy(); + }); +}); + +describe.skip('my other beverage', () => { + // ... will be skipped +}); +``` + +Using `describe.skip` is often a cleaner alternative to temporarily commenting out a chunk of tests. + +### `describe.skip.each(table)(name, fn)` + +Also under the aliases: `xdescribe.each(table)(name, fn)` and `` xdescribe.each`table`(name, fn) `` + +Use `describe.skip.each` if you want to stop running a suite of data driven tests. + +`describe.skip.each` is available with two APIs: + +#### `describe.skip.each(table)(name, fn)` + +```js +describe.skip.each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +])('.add(%i, %i)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); // will not be ran + }); +}); + +test('will be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +#### `` describe.skip.each`table`(name, fn) `` + +```js +describe.skip.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`('returns $expected when $a is added $b', ({a, b, expected}) => { + test('will not be ran', () => { + expect(a + b).toBe(expected); // will not be ran + }); +}); + +test('will be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +### `test(name, fn, timeout)` + +Also under the alias: `it(name, fn, timeout)` + +All you need in a test file is the `test` method which runs a test. For example, let's say there's a function `inchesOfRain()` that should be zero. Your whole test could be: + +```js +test('did not rain', () => { + expect(inchesOfRain()).toBe(0); +}); +``` + +The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ + +> Note: If a **promise is returned** from `test`, Jest will wait for the promise to resolve before letting the test complete. Jest will also wait if you **provide an argument to the test function**, usually called `done`. This could be handy when you want to test callbacks. See how to test async code [here](TestingAsyncCode.md#callbacks). + +For example, let's say `fetchBeverageList()` returns a promise that is supposed to resolve to a list that has `lemon` in it. You can test this with: + +```js +test('has lemon in it', () => { + return fetchBeverageList().then(list => { + expect(list).toContain('lemon'); + }); +}); +``` + +Even though the call to `test` will return right away, the test doesn't complete until the promise resolves as well. + +### `test.each(table)(name, fn, timeout)` + +Also under the alias: `it.each(table)(name, fn)` and `` it.each`table`(name, fn) `` + +Use `test.each` if you keep duplicating the same test with different data. `test.each` allows you to write the test once and pass data in. + +`test.each` is available with two APIs: + +#### 1. `test.each(table)(name, fn, timeout)` + +- `table`: `Array` of Arrays with the arguments that are passed into the test `fn` for each row. + - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` +- `name`: `String` the title of the test block. + - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. +- `fn`: `Function` the test to be ran, this is the function that will receive the parameters in each row as function arguments. +- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. _Note: The default timeout is 5 seconds._ + +Example: + +```js +test.each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +])('.add(%i, %i)', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +#### 2. `` test.each`table`(name, fn, timeout) `` + +- `table`: `Tagged Template Literal` + - First row of variable name column headings separated with `|` + - One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. +- `name`: `String` the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions. + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` +- `fn`: `Function` the test to be ran, this is the function that will receive the test data object. +- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. _Note: The default timeout is 5 seconds._ + +Example: + +```js +test.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`('returns $expected when $a is added $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +### `test.only(name, fn, timeout)` + +Also under the aliases: `ftest(name, fn, timeout)`, `it.only(name, fn, timeout)`, and `fit(name, fn, timeout)` + +When you are debugging a large test file, you will often only want to run a subset of tests. You can use `.only` to specify which tests are the only ones you want to run in that test file. + +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ + +For example, let's say you had these tests: + +```js +test.only('it is raining', () => { + expect(inchesOfRain()).toBeGreaterThan(0); +}); + +test('it is not snowing', () => { + expect(inchesOfSnow()).toBe(0); +}); +``` + +Only the "it is raining" test will run in that test file, since it is run with `test.only`. + +Usually you wouldn't check code using `test.only` into source control - you would use it for debugging, and remove it once you have fixed the broken tests. + +### `test.only.each(table)(name, fn)` + +Also under the aliases: `ftest.each(table)(name, fn)`, `it.only.each(table)(name, fn)`, `fit.each(table)(name, fn)`, `` ftest.each`table`(name, fn) ``, `` it.only.each`table`(name, fn) `` and `` fit.each`table`(name, fn) `` + +Use `test.only.each` if you want to only run specific tests with different test data. + +`test.only.each` is available with two APIs: + +#### `test.only.each(table)(name, fn)` + +```js +test.only.each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +])('.add(%i, %i)', (a, b, expected) => { + expect(a + b).toBe(expected); +}); + +test('will not be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +#### `` test.only.each`table`(name, fn) `` + +```js +test.only.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`('returns $expected when $a is added $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); + +test('will not be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +### `test.skip(name, fn)` + +Also under the aliases: `it.skip(name, fn)`, `xit(name, fn)`, and `xtest(name, fn)` + +When you are maintaining a large codebase, you may sometimes find a test that is temporarily broken for some reason. If you want to skip running this test, but you don't want to delete this code, you can use `test.skip` to specify some tests to skip. + +For example, let's say you had these tests: + +```js +test('it is raining', () => { + expect(inchesOfRain()).toBeGreaterThan(0); +}); + +test.skip('it is not snowing', () => { + expect(inchesOfSnow()).toBe(0); +}); +``` + +Only the "it is raining" test will run, since the other test is run with `test.skip`. + +You could comment the test out, but it's often a bit nicer to use `test.skip` because it will maintain indentation and syntax highlighting. + +### `test.skip.each(table)(name, fn)` + +Also under the aliases: `it.skip.each(table)(name, fn)`, `xit.each(table)(name, fn)`, `xtest.each(table)(name, fn)`, `` it.skip.each`table`(name, fn) ``, `` xit.each`table`(name, fn) `` and `` xtest.each`table`(name, fn) `` + +Use `test.skip.each` if you want to stop running a collection of data driven tests. + +`test.skip.each` is available with two APIs: + +#### `test.skip.each(table)(name, fn)` + +```js +test.skip.each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +])('.add(%i, %i)', (a, b, expected) => { + expect(a + b).toBe(expected); // will not be ran +}); + +test('will be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +#### `` test.skip.each`table`(name, fn) `` + +```js +test.skip.each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`('returns $expected when $a is added $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); // will not be ran +}); + +test('will be ran', () => { + expect(1 / 0).toBe(Infinity); +}); +``` + +### `test.todo(name)` + +Also under the alias: `it.todo(name)` + +Use `test.todo` when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo. + +_Note_: If you supply a test callback function then the `test.todo` will throw an error. If you have already implemented the test and it is broken and you do not want it to run, then use `test.skip` instead. + +#### API + +- `name`: `String` the title of the test plan. + +Example: + +```js +const add = (a, b) => a + b; + +test.todo('add should be associative'); +``` diff --git a/website/versioned_docs/version-25.5/JestObjectAPI.md b/website/versioned_docs/version-25.5/JestObjectAPI.md new file mode 100644 index 000000000000..04f2414db41a --- /dev/null +++ b/website/versioned_docs/version-25.5/JestObjectAPI.md @@ -0,0 +1,672 @@ +--- +id: version-25.5-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. It can also be imported explicitly by via `import {jest} from '@jest/globals'`. + +## 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.5/JestPlatform.md b/website/versioned_docs/version-25.5/JestPlatform.md new file mode 100644 index 000000000000..1b2ddf710cd2 --- /dev/null +++ b/website/versioned_docs/version-25.5/JestPlatform.md @@ -0,0 +1,175 @@ +--- +id: version-25.5-jest-platform +title: Jest Platform +original_id: jest-platform +--- + +You can cherry pick specific features of Jest and use them as standalone packages. Here's a list of the available packages: + +## jest-changed-files + +Tool for identifying modified files in a git/hg repository. Exports two functions: + +- `getChangedFilesForRoots` returns a promise that resolves to an object with the changed files and repos. +- `findRepos` returns a promise that resolves to a set of repositories contained in the specified path. + +### Example + +```javascript +const {getChangedFilesForRoots} = require('jest-changed-files'); + +// print the set of modified files since last commit in the current repo +getChangedFilesForRoots(['./'], { + lastCommit: true, +}).then(result => console.log(result.changedFiles)); +``` + +You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-changed-files/README.md). + +## jest-diff + +Tool for visualizing changes in data. Exports a function that compares two values of any type and returns a "pretty-printed" string illustrating the difference between the two arguments. + +### Example + +```javascript +const diff = require('jest-diff'); + +const a = {a: {b: {c: 5}}}; +const b = {a: {b: {c: 6}}}; + +const result = diff(a, b); + +// print diff +console.log(result); +``` + +## jest-docblock + +Tool for extracting and parsing the comments at the top of a JavaScript file. Exports various functions to manipulate the data inside the comment block. + +### Example + +```javascript +const {parseWithComments} = require('jest-docblock'); + +const code = ` +/** + * This is a sample + * + * @flow + */ + + console.log('Hello World!'); +`; + +const parsed = parseWithComments(code); + +// prints an object with two attributes: comments and pragmas. +console.log(parsed); +``` + +You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-docblock/README.md). + +## jest-get-type + +Module that identifies the primitive type of any JavaScript value. Exports a function that returns a string with the type of the value passed as argument. + +### Example + +```javascript +const getType = require('jest-get-type'); + +const array = [1, 2, 3]; +const nullValue = null; +const undefinedValue = undefined; + +// prints 'array' +console.log(getType(array)); +// prints 'null' +console.log(getType(nullValue)); +// prints 'undefined' +console.log(getType(undefinedValue)); +``` + +## jest-validate + +Tool for validating configurations submitted by users. Exports a function that takes two arguments: the user's configuration and an object containing an example configuration and other options. The return value is an object with two attributes: + +- `hasDeprecationWarnings`, a boolean indicating whether the submitted configuration has deprecation warnings, +- `isValid`, a boolean indicating whether the configuration is correct or not. + +### Example + +```javascript +const {validate} = require('jest-validate'); + +const configByUser = { + transform: '/node_modules/my-custom-transform', +}; + +const result = validate(configByUser, { + comment: ' Documentation: http://custom-docs.com', + exampleConfig: {transform: '/node_modules/babel-jest'}, +}); + +console.log(result); +``` + +You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-validate/README.md). + +## jest-worker + +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 + +```javascript +// heavy-task.js + +module.exports = { + myHeavyTask: args => { + // long running CPU intensive task. + }, +}; +``` + +```javascript +// main.js + +async function main() { + const worker = new Worker(require.resolve('./heavy-task.js')); + + // run 2 tasks in parallel with different arguments + const results = await Promise.all([ + worker.myHeavyTask({foo: 'bar'}), + worker.myHeavyTask({bar: 'foo'}), + ]); + + console.log(results); +} + +main(); +``` + +You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-worker/README.md). + +## pretty-format + +Exports a function that converts any JavaScript value into a human-readable string. Supports all built-in JavaScript types out of the box and allows extension for application-specific types via user-defined plugins. + +### Example + +```javascript +const prettyFormat = require('pretty-format'); + +const val = {object: {}}; +val.circularReference = val; +val[Symbol('foo')] = 'foo'; +val.map = new Map([['prop', 'value']]); +val.array = [-0, Infinity, NaN]; + +console.log(prettyFormat(val)); +``` + +You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/master/packages/pretty-format/README.md). diff --git a/website/versions.json b/website/versions.json index 309b51aa700a..359fa3ec8a76 100644 --- a/website/versions.json +++ b/website/versions.json @@ -1,4 +1,5 @@ [ + "25.5", "25.3", "25.1", "24.x",