# Table of Contents - [Getting Started · Jest](#getting-started-jest) - [Code Transformation · Jest](#code-transformation-jest) - [Environment Variables · Jest](#environment-variables-jest) - [Testing Asynchronous Code · Jest](#testing-asynchronous-code-jest) - [Jest CLI Options · Jest](#jest-cli-options-jest) - [Jest Community · Jest](#jest-community-jest) - [Architecture · Jest](#architecture-jest) - [Testing Web Frameworks · Jest](#testing-web-frameworks-jest) - [From v28 to v29 · Jest](#from-v28-to-v29-jest) - [Bypassing module mocks · Jest](#bypassing-module-mocks-jest) - [Using with DynamoDB · Jest](#using-with-dynamodb-jest) - [Globals · Jest](#globals-jest) - [Getting Started · Jest](#getting-started-jest) - [ECMAScript Modules · Jest](#ecmascript-modules-jest) - [Jest Platform · Jest](#jest-platform-jest) - [Environment Variables · Jest](#environment-variables-jest) - [Testing React Native Apps · Jest](#testing-react-native-apps-jest) - [Testing Web Frameworks · Jest](#testing-web-frameworks-jest) - [More Resources · Jest](#more-resources-jest) - [Environment Variables · Jest](#environment-variables-jest) - [Testing Web Frameworks · Jest](#testing-web-frameworks-jest) - [Testing React Apps · Jest](#testing-react-apps-jest) - [From v28 to v29 · Jest](#from-v28-to-v29-jest) - [From v29 to v30 · Jest](#from-v29-to-v30-jest) - [Testing React Native Apps · Jest](#testing-react-native-apps-jest) - [From v29 to v30 · Jest](#from-v29-to-v30-jest) - [Jest Community · Jest](#jest-community-jest) - [Testing React Native Apps · Jest](#testing-react-native-apps-jest) - [Testing Asynchronous Code · Jest](#testing-asynchronous-code-jest) - [Jest Community · Jest](#jest-community-jest) - [Code Transformation · Jest](#code-transformation-jest) - [Testing Asynchronous Code · Jest](#testing-asynchronous-code-jest) - [Code Transformation · Jest](#code-transformation-jest) - [Using Matchers · Jest](#using-matchers-jest) - [Testing React Apps · Jest](#testing-react-apps-jest) - [Jest Platform · Jest](#jest-platform-jest) - [Jest Platform · Jest](#jest-platform-jest) - [Jest CLI Options · Jest](#jest-cli-options-jest) - [Jest CLI Options · Jest](#jest-cli-options-jest) - [From v28 to v29 · Jest](#from-v28-to-v29-jest) - [Setup and Teardown · Jest](#setup-and-teardown-jest) - [Testing React Apps · Jest](#testing-react-apps-jest) - [More Resources · Jest](#more-resources-jest) - [More Resources · Jest](#more-resources-jest) - [Getting Started · Jest](#getting-started-jest) - [Setup and Teardown · Jest](#setup-and-teardown-jest) - [Using Matchers · Jest](#using-matchers-jest) - [Using Matchers · Jest](#using-matchers-jest) - [Mock Functions · Jest](#mock-functions-jest) - [Architecture · Jest](#architecture-jest) - [Mock Functions · Jest](#mock-functions-jest) --- # Getting Started · Jest [Skip to main content](https://jestjs.io/docs/getting-started#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . Version: 30.0 On this page Install Jest using your favorite package manager: * npm * Yarn * pnpm npm install --save-dev jest yarn add --dev jest pnpm add --save-dev jest Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a `sum.js` file: function sum(a, b) { return a + b;}module.exports = sum; Then, create a file named `sum.test.js`. This will contain our actual test: const sum = require('./sum');test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3);}); Add the following section to your `package.json`: { "scripts": { "test": "jest" }} Finally, run `yarn test` or `npm test` and Jest will print this message: PASS ./sum.test.js✓ adds 1 + 2 to equal 3 (5ms) **You just successfully wrote your first test using Jest!** This test used `expect` and `toBe` to test that two values were exactly identical. To learn about the other things that Jest can test, see [Using Matchers](https://jestjs.io/docs/using-matchers) . Running from command line[​](https://jestjs.io/docs/getting-started#running-from-command-line "Direct link to Running from command line") ------------------------------------------------------------------------------------------------------------------------------------------ You can run Jest directly from the CLI (if it's globally available in your `PATH`, e.g. by `yarn global add jest` or `npm install jest --global`) with a variety of useful options. Here's how to run Jest on files matching `my-test`, using `config.json` as a configuration file and display a native OS notification after the run: jest my-test --notify --config=config.json If you'd like to learn more about running `jest` through the command line, take a look at the [Jest CLI Options](https://jestjs.io/docs/cli) page. Additional Configuration[​](https://jestjs.io/docs/getting-started#additional-configuration "Direct link to Additional Configuration") --------------------------------------------------------------------------------------------------------------------------------------- ### Generate a basic configuration file[​](https://jestjs.io/docs/getting-started#generate-a-basic-configuration-file "Direct link to Generate a basic configuration file") Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option: * npm * Yarn * pnpm npm init jest@latest yarn create jest pnpm create jest ### Using Babel[​](https://jestjs.io/docs/getting-started#using-babel "Direct link to Using Babel") To use [Babel](https://babeljs.io/) , install required dependencies: * npm * Yarn * pnpm npm install --save-dev babel-jest @babel/core @babel/preset-env yarn add --dev babel-jest @babel/core @babel/preset-env pnpm add --save-dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: babel.config.js module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]],}; The ideal configuration for Babel will depend on your project. See [Babel's docs](https://babeljs.io/docs/en/) for more details. **Making your Babel config jest-aware** Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. babel.config.js module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. return { // ... };}; note `babel-jest` is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the `transform` configuration option: jest.config.js module.exports = { transform: {},}; Using with bundlers[​](https://jestjs.io/docs/getting-started#using-with-bundlers "Direct link to Using with bundlers") ------------------------------------------------------------------------------------------------------------------------ Most of the time you do not need to do anything special to work with different bundlers - the exception is if you have some plugin or configuration which generates files or have custom file resolution rules. ### Using webpack[​](https://jestjs.io/docs/getting-started#using-webpack "Direct link to Using webpack") Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the [webpack guide](https://jestjs.io/docs/webpack) to get started. ### Using Vite[​](https://jestjs.io/docs/getting-started#using-vite "Direct link to Using Vite") Jest is not supported by Vite due to incompatibilities with the Vite [plugin system](https://github.com/vitejs/vite/issues/1955#issuecomment-776009094) . There are examples for Jest integration with Vite in the [vite-jest](https://github.com/sodatea/vite-jest) library. However, this library is not compatible with versions of Vite later than 2.4.2. One alternative is [Vitest](https://vitest.dev/) which has an API compatible Jest. ### Using Parcel[​](https://jestjs.io/docs/getting-started#using-parcel "Direct link to Using Parcel") Jest can be used in projects that use [parcel-bundler](https://parceljs.org/) to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official [docs](https://parceljs.org/docs/) to get started. ### Using TypeScript[​](https://jestjs.io/docs/getting-started#using-typescript "Direct link to Using TypeScript") #### Via `babel`[​](https://jestjs.io/docs/getting-started#via-babel "Direct link to via-babel") Jest supports TypeScript, via Babel. First, make sure you followed the instructions on [using Babel](https://jestjs.io/docs/getting-started#using-babel) above. Next, install the `@babel/preset-typescript`: * npm * Yarn * pnpm npm install --save-dev @babel/preset-typescript yarn add --dev @babel/preset-typescript pnpm add --save-dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. babel.config.js module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], '@babel/preset-typescript', ],}; However, there are some [caveats](https://babeljs.io/docs/en/babel-plugin-transform-typescript#caveats) to using TypeScript with Babel. Because TypeScript support in Babel is purely transpilation, Jest will not type-check your tests as they are run. If you want that, you can use [ts-jest](https://github.com/kulshekhar/ts-jest) instead, or just run the TypeScript compiler [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) separately (or as part of your build process). #### Via `ts-jest`[​](https://jestjs.io/docs/getting-started#via-ts-jest "Direct link to via-ts-jest") [ts-jest](https://github.com/kulshekhar/ts-jest) is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript. * npm * Yarn * pnpm npm install --save-dev ts-jest yarn add --dev ts-jest pnpm add --save-dev ts-jest In order for Jest to transpile TypeScript with `ts-jest`, you may also need to create a [configuration](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation#jest-config-file) file. #### Type definitions[​](https://jestjs.io/docs/getting-started#type-definitions "Direct link to Type definitions") There are two ways to have [Jest global APIs](https://jestjs.io/docs/api) typed for test files written in TypeScript. You can use type definitions which ships with Jest and will update each time you update Jest. Install the `@jest/globals` package: * npm * Yarn * pnpm npm install --save-dev @jest/globals yarn add --dev @jest/globals pnpm add --save-dev @jest/globals And import the APIs from it: sum.test.ts import {describe, expect, test} from '@jest/globals';import {sum} from './sum';describe('sum module', () => { test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });}); tip See the additional usage documentation of [`describe.each`/`test.each`](https://jestjs.io/docs/api#typescript-usage) and [`mock functions`](https://jestjs.io/docs/mock-function-api#typescript-usage) . Or you may choose to install the [`@types/jest`](https://npmjs.com/package/@types/jest) package. It provides types for Jest globals without a need to import them. * npm * Yarn * pnpm npm install --save-dev @types/jest yarn add --dev @types/jest pnpm add --save-dev @types/jest info `@types/jest` is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) , hence the latest Jest features or versions may not be covered yet. Try to match versions of Jest and `@types/jest` as closely as possible. For example, if you are using Jest `27.4.0` then installing `27.4.x` of `@types/jest` is ideal. ### Using ESLint[​](https://jestjs.io/docs/getting-started#using-eslint "Direct link to Using ESLint") Jest can be used with ESLint without any further configuration as long as you import the [Jest global helpers](https://jestjs.io/docs/api) (`describe`, `it`, etc.) from `@jest/globals` before using them in your test file. This is necessary to avoid `no-undef` errors from ESLint, which doesn't know about the Jest globals. If you'd like to avoid these imports, you can configure your [ESLint environment](https://eslint.org/docs/latest/use/configure/language-options#specifying-environments) to support these globals by adding the `jest` environment: import {defineConfig} from 'eslint/config';import globals from 'globals';export default defineConfig([ { files: ['**/*.js'], languageOptions: { globals: { ...globals.jest, }, }, rules: { 'no-unused-vars': 'warn', 'no-undef': 'warn', }, },]); Or use [`eslint-plugin-jest`](https://github.com/jest-community/eslint-plugin-jest) , which has a similar effect: { "overrides": [ { "files": ["tests/**/*"], "plugins": ["jest"], "env": { "jest/globals": true } } ]} * [Running from command line](https://jestjs.io/docs/getting-started#running-from-command-line) * [Additional Configuration](https://jestjs.io/docs/getting-started#additional-configuration) * [Generate a basic configuration file](https://jestjs.io/docs/getting-started#generate-a-basic-configuration-file) * [Using Babel](https://jestjs.io/docs/getting-started#using-babel) * [Using with bundlers](https://jestjs.io/docs/getting-started#using-with-bundlers) * [Using webpack](https://jestjs.io/docs/getting-started#using-webpack) * [Using Vite](https://jestjs.io/docs/getting-started#using-vite) * [Using Parcel](https://jestjs.io/docs/getting-started#using-parcel) * [Using TypeScript](https://jestjs.io/docs/getting-started#using-typescript) * [Using ESLint](https://jestjs.io/docs/getting-started#using-eslint) --- # Code Transformation · Jest [Skip to main content](https://jestjs.io/docs/29.7/code-transformation#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/code-transformation) ** (30.0). Version: 29.7 On this page Jest runs the code in your project as JavaScript, but if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates) then you'll need to transform that code into plain JavaScript, similar to what you would do when building for browsers. Jest supports this via the [`transform`](https://jestjs.io/docs/29.7/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object) configuration option. A transformer is a module that provides a method for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by Node, you might plug in a code preprocessor that would transpile a future version of JavaScript to a current one. Jest will cache the result of a transformation and attempt to invalidate that result based on a number of factors, such as the source of the file being transformed and changing configuration. Defaults[​](https://jestjs.io/docs/29.7/code-transformation#defaults "Direct link to Defaults") ------------------------------------------------------------------------------------------------ Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) . It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](https://jestjs.io/docs/29.7/manual-mocks#using-with-es-module-imports) . tip Remember to include the default `babel-jest` transformer explicitly, if you wish to use it alongside with additional code preprocessors: "transform": { "\\.[jt]sx?$": "babel-jest", "\\.css$": "some-css-transformer",} Writing custom transformers[​](https://jestjs.io/docs/29.7/code-transformation#writing-custom-transformers "Direct link to Writing custom transformers") --------------------------------------------------------------------------------------------------------------------------------------------------------- You can write your own transformer. The API of a transformer is as follows: interface TransformOptions { supportsDynamicImport: boolean; supportsExportNamespaceFrom: boolean; /** * The value is: * - `false` if Jest runs without Node ESM flag `--experimental-vm-modules` * - `true` if the file extension is defined in [extensionsToTreatAsEsm](Configuration.md#extensionstotreatasesm-arraystring) * and Jest runs with Node ESM flag `--experimental-vm-modules` * * See more at https://jestjs.io/docs/next/ecmascript-modules */ supportsStaticESM: boolean; supportsTopLevelAwait: boolean; instrument: boolean; /** Cached file system which is used by `jest-runtime` to improve performance. */ cacheFS: Map; /** Jest configuration of currently running project. */ config: ProjectConfig; /** Stringified version of the `config` - useful in cache busting. */ configString: string; /** Transformer configuration passed through `transform` option by the user. */ transformerConfig: TransformerConfig;}type TransformedSource = { code: string; map?: RawSourceMap | string | null;};interface SyncTransformer { canInstrument?: boolean; getCacheKey?: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => string; getCacheKeyAsync?: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => Promise; process: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => TransformedSource; processAsync?: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => Promise;}interface AsyncTransformer { canInstrument?: boolean; getCacheKey?: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => string; getCacheKeyAsync?: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => Promise; process?: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => TransformedSource; processAsync: ( sourceText: string, sourcePath: string, options: TransformOptions, ) => Promise;}type Transformer = | SyncTransformer | AsyncTransformer;type TransformerCreator< X extends Transformer, TransformerConfig = unknown,> = (transformerConfig?: TransformerConfig) => X;type TransformerFactory = { createTransformer: TransformerCreator;}; note The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). There are a couple of ways you can import code into Jest - using Common JS (`require`) or ECMAScript Modules (`import` - which exists in static and dynamic versions). Jest passes files through code transformation on demand (for instance when a `require` or `import` is evaluated). This process, also known as "transpilation", might happen _synchronously_ (in the case of `require`), or _asynchronously_ (in the case of `import` or `import()`, the latter of which also works from Common JS modules). For this reason, the interface exposes both pairs of methods for asynchronous and synchronous processes: `process{Async}` and `getCacheKey{Async}`. The latter is called to figure out if we need to call `process{Async}` at all. Asynchronous transpilation can fall back to the synchronous `process` call if `processAsync` is unimplemented, but synchronous transpilation cannot use the asynchronous `processAsync` call. If your codebase is ESM only, implementing the async variants are sufficient. Otherwise, if any code is loaded through `require` (including `createRequire` from within ESM), then you need to implement the synchronous `process` variant. Be aware that `node_modules` is not transpiled with default config, the `transformIgnorePatterns` setting must be modified in order to do so. Semi-related to this are the supports flags we pass (see `CallerTransformOptions` above), but those should be used within the transform to figure out if it should return ESM or CJS, and has no direct bearing on sync vs async Though not required, we _highly recommend_ implementing `getCacheKey` as well, so we do not waste resources transpiling when we could have read its previous result from disk. You can use [`@jest/create-cache-key-function`](https://www.npmjs.com/package/@jest/create-cache-key-function) to help implement it. Instead of having your custom transformer implement the `Transformer` interface directly, you can choose to export `createTransformer`, a factory function to dynamically create transformers. This is to allow having a transformer config in your jest config. note [ECMAScript module](https://jestjs.io/docs/29.7/ecmascript-modules) support is indicated by the passed in `supports*` options. Specifically `supportsDynamicImport: true` means the transformer can return `import()` expressions, which is supported by both ESM and CJS. If `supportsStaticESM: true` it means top level `import` statements are supported and the code will be interpreted as ESM and not CJS. See [Node's docs](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs) for details on the differences. tip Make sure `process{Async}` method returns source map alongside with transformed code, so it is possible to report line information accurately in code coverage and test errors. Inline source maps also work but are slower. During the development of a transformer it can be useful to run Jest with `--no-cache` to frequently [delete cache](https://jestjs.io/docs/29.7/troubleshooting#caching-issues) . ### Examples[​](https://jestjs.io/docs/29.7/code-transformation#examples "Direct link to Examples") ### TypeScript with type checking[​](https://jestjs.io/docs/29.7/code-transformation#typescript-with-type-checking "Direct link to TypeScript with type checking") While `babel-jest` by default will transpile TypeScript files, Babel will not verify the types. If you want that you can use [`ts-jest`](https://github.com/kulshekhar/ts-jest) . #### Transforming images to their path[​](https://jestjs.io/docs/29.7/code-transformation#transforming-images-to-their-path "Direct link to Transforming images to their path") Importing images is a way to include them in your browser bundle, but they are not valid JavaScript. One way of handling it in Jest is to replace the imported value with its filename. fileTransformer.js const path = require('path');module.exports = { process(sourceText, sourcePath, options) { return { code: `module.exports = ${JSON.stringify(path.basename(sourcePath))};`, }; },}; jest.config.js module.exports = { transform: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '/fileTransformer.js', },}; * [Defaults](https://jestjs.io/docs/29.7/code-transformation#defaults) * [Writing custom transformers](https://jestjs.io/docs/29.7/code-transformation#writing-custom-transformers) * [Examples](https://jestjs.io/docs/29.7/code-transformation#examples) * [TypeScript with type checking](https://jestjs.io/docs/29.7/code-transformation#typescript-with-type-checking) --- # Environment Variables · Jest [Skip to main content](https://jestjs.io/docs/29.7/environment-variables#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/environment-variables) ** (30.0). Version: 29.7 On this page Jest sets the following environment variables: ### `NODE_ENV`[​](https://jestjs.io/docs/29.7/environment-variables#node_env "Direct link to node_env") Set to `'test'` if it's not already set to something else. ### `JEST_WORKER_ID`[​](https://jestjs.io/docs/29.7/environment-variables#jest_worker_id "Direct link to jest_worker_id") Each worker process is assigned a unique id (index-based that starts with `1`). This is set to `1` for all tests when [`runInBand`](https://jestjs.io/docs/29.7/cli#--runinband) is set to true. * [`NODE_ENV`](https://jestjs.io/docs/29.7/environment-variables#node_env) * [`JEST_WORKER_ID`](https://jestjs.io/docs/29.7/environment-variables#jest_worker_id) --- # Testing Asynchronous Code · Jest [Skip to main content](https://jestjs.io/docs/29.7/asynchronous#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/asynchronous) ** (30.0). Version: 29.7 On this page It's common in JavaScript for code to run asynchronously. When you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test. Jest has several ways to handle this. Promises[​](https://jestjs.io/docs/29.7/asynchronous#promises "Direct link to Promises") ----------------------------------------------------------------------------------------- Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will fail. For example, let's say that `fetchData` returns a promise that is supposed to resolve to the string `'peanut butter'`. We could test it with: test('the data is peanut butter', () => { return fetchData().then(data => { expect(data).toBe('peanut butter'); });}); Async/Await[​](https://jestjs.io/docs/29.7/asynchronous#asyncawait "Direct link to Async/Await") ------------------------------------------------------------------------------------------------- Alternatively, you can use `async` and `await` in your tests. To write an async test, use the `async` keyword in front of the function passed to `test`. For example, the same `fetchData` scenario can be tested with: test('the data is peanut butter', async () => { const data = await fetchData(); expect(data).toBe('peanut butter');});test('the fetch fails with an error', async () => { expect.assertions(1); try { await fetchData(); } catch (error) { expect(error).toMatch('error'); }}); You can combine `async` and `await` with `.resolves` or `.rejects`. test('the data is peanut butter', async () => { await expect(fetchData()).resolves.toBe('peanut butter');});test('the fetch fails with an error', async () => { await expect(fetchData()).rejects.toMatch('error');}); In these cases, `async` and `await` are effectively syntactic sugar for the same logic as the promises example uses. caution Be sure to return (or `await`) the promise - if you omit the `return`/`await` statement, your test will complete before the promise returned from `fetchData` resolves or rejects. If you expect a promise to be rejected, use the `.catch` method. Make sure to add `expect.assertions` to verify that a certain number of assertions are called. Otherwise, a fulfilled promise would not fail the test. test('the fetch fails with an error', () => { expect.assertions(1); return fetchData().catch(error => expect(error).toMatch('error'));}); Callbacks[​](https://jestjs.io/docs/29.7/asynchronous#callbacks "Direct link to Callbacks") -------------------------------------------------------------------------------------------- If you don't use promises, you can use callbacks. For example, let's say that `fetchData`, instead of returning a promise, expects a callback, i.e. fetches some data and calls `callback(null, data)` when it is complete. You want to test that this returned data is the string `'peanut butter'`. By default, Jest tests complete once they reach the end of their execution. That means this test will _not_ work as intended: // Don't do this!test('the data is peanut butter', () => { function callback(error, data) { if (error) { throw error; } expect(data).toBe('peanut butter'); } fetchData(callback);}); The problem is that the test will complete as soon as `fetchData` completes, before ever calling the callback. There is an alternate form of `test` that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called `done`. Jest will wait until the `done` callback is called before finishing the test. test('the data is peanut butter', done => { function callback(error, data) { if (error) { done(error); return; } try { expect(data).toBe('peanut butter'); done(); } catch (error) { done(error); } } fetchData(callback);}); If `done()` is never called, the test will fail (with timeout error), which is what you want to happen. If the `expect` statement fails, it throws an error and `done()` is not called. If we want to see in the test log why it failed, we have to wrap `expect` in a `try` block and pass the error in the `catch` block to `done`. Otherwise, we end up with an opaque timeout error that doesn't show what value was received by `expect(data)`. caution Jest will throw an error, if the same test function is passed a `done()` callback and returns a promise. This is done as a precaution to avoid memory leaks in your tests. `.resolves` / `.rejects`[​](https://jestjs.io/docs/29.7/asynchronous#resolves--rejects "Direct link to resolves--rejects") --------------------------------------------------------------------------------------------------------------------------- You can also use the `.resolves` matcher in your expect statement, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail. test('the data is peanut butter', () => { return expect(fetchData()).resolves.toBe('peanut butter');}); Be sure to return the assertion—if you omit this `return` statement, your test will complete before the promise returned from `fetchData` is resolved and then() has a chance to execute the callback. If you expect a promise to be rejected, use the `.rejects` matcher. It works analogically to the `.resolves` matcher. If the promise is fulfilled, the test will automatically fail. test('the fetch fails with an error', () => { return expect(fetchData()).rejects.toMatch('error');}); None of these forms is particularly superior to the others, and you can mix and match them across a codebase or even in a single file. It just depends on which style you feel makes your tests simpler. * [Promises](https://jestjs.io/docs/29.7/asynchronous#promises) * [Async/Await](https://jestjs.io/docs/29.7/asynchronous#asyncawait) * [Callbacks](https://jestjs.io/docs/29.7/asynchronous#callbacks) * [`.resolves` / `.rejects`](https://jestjs.io/docs/29.7/asynchronous#resolves--rejects) --- # Jest CLI Options · Jest [Skip to main content](https://jestjs.io/docs/29.7/cli#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/cli) ** (30.0). Version: 29.7 On this page The `jest` command line runner has a number of useful options. You can run `jest --help` to view all available options. Many of the options shown below can also be used together to run tests exactly the way you want. Every one of Jest's [Configuration](https://jestjs.io/docs/29.7/configuration) options can also be specified through the CLI. Here is a brief overview: Running from the command line[​](https://jestjs.io/docs/29.7/cli#running-from-the-command-line "Direct link to Running from the command line") ----------------------------------------------------------------------------------------------------------------------------------------------- Run all tests (default): jest Run only the tests that were specified with a pattern or filename: jest my-test #orjest path/to/my-test.js Run tests related to changed files based on hg/git (uncommitted files): jest -o Run tests related to `path/to/fileA.js` and `path/to/fileB.js`: jest --findRelatedTests path/to/fileA.js path/to/fileB.js Run tests that match this spec name (match against the name in `describe` or `test`, basically). jest -t name-of-spec Run watch mode: jest --watch #runs jest -o by defaultjest --watchAll #runs all tests Watch mode also enables to specify the name or path to a file to focus on a specific set of tests. Using with package manager[​](https://jestjs.io/docs/29.7/cli#using-with-package-manager "Direct link to Using with package manager") -------------------------------------------------------------------------------------------------------------------------------------- If you run Jest via your package manager, you can still pass the command line arguments directly as Jest arguments. Instead of: jest -u -t="ColorPicker" you can use: * npm * Yarn * pnpm npm test -- -u -t="ColorPicker" yarn test -u -t="ColorPicker" pnpm test -u -t="ColorPicker" Camelcase & dashed args support[​](https://jestjs.io/docs/29.7/cli#camelcase--dashed-args-support "Direct link to Camelcase & dashed args support") ---------------------------------------------------------------------------------------------------------------------------------------------------- Jest supports both camelcase and dashed arg formats. The following examples will have an equal result: jest --collect-coveragejest --collectCoverage Arguments can also be mixed: jest --update-snapshot --detectOpenHandles Options[​](https://jestjs.io/docs/29.7/cli#options "Direct link to Options") ----------------------------------------------------------------------------- note CLI options take precedence over values from the [Configuration](https://jestjs.io/docs/29.7/configuration) . * [Camelcase & dashed args support](https://jestjs.io/docs/29.7/cli#camelcase--dashed-args-support) * [Options](https://jestjs.io/docs/29.7/cli#options) * [Reference](https://jestjs.io/docs/29.7/cli#reference) * [`jest `](https://jestjs.io/docs/29.7/cli#jest-regexfortestfiles) * [`--bail[=]`](https://jestjs.io/docs/29.7/cli#--bailn) * [`--cache`](https://jestjs.io/docs/29.7/cli#--cache) * [`--changedFilesWithAncestor`](https://jestjs.io/docs/29.7/cli#--changedfileswithancestor) * [`--changedSince`](https://jestjs.io/docs/29.7/cli#--changedsince) * [`--ci`](https://jestjs.io/docs/29.7/cli#--ci) * [`--clearCache`](https://jestjs.io/docs/29.7/cli#--clearcache) * [`--clearMocks`](https://jestjs.io/docs/29.7/cli#--clearmocks) * [`--collectCoverageFrom=`](https://jestjs.io/docs/29.7/cli#--collectcoveragefromglob) * [`--colors`](https://jestjs.io/docs/29.7/cli#--colors) * [`--config=`](https://jestjs.io/docs/29.7/cli#--configpath) * [`--coverage[=]`](https://jestjs.io/docs/29.7/cli#--coverageboolean) * [`--coverageDirectory=`](https://jestjs.io/docs/29.7/cli#--coveragedirectorypath) * [`--coverageProvider=`](https://jestjs.io/docs/29.7/cli#--coverageproviderprovider) * [`--debug`](https://jestjs.io/docs/29.7/cli#--debug) * [`--detectOpenHandles`](https://jestjs.io/docs/29.7/cli#--detectopenhandles) * [`--env=`](https://jestjs.io/docs/29.7/cli#--envenvironment) * [`--errorOnDeprecated`](https://jestjs.io/docs/29.7/cli#--errorondeprecated) * [`--expand`](https://jestjs.io/docs/29.7/cli#--expand) * [`--filter=`](https://jestjs.io/docs/29.7/cli#--filterfile) * [`--findRelatedTests `](https://jestjs.io/docs/29.7/cli#--findrelatedtests-spaceseparatedlistofsourcefiles) * [`--forceExit`](https://jestjs.io/docs/29.7/cli#--forceexit) * [`--help`](https://jestjs.io/docs/29.7/cli#--help) * [`--ignoreProjects ... `](https://jestjs.io/docs/29.7/cli#--ignoreprojects-project1--projectn) * [`--init`](https://jestjs.io/docs/29.7/cli#--init) * [`--injectGlobals`](https://jestjs.io/docs/29.7/cli#--injectglobals) * [`--json`](https://jestjs.io/docs/29.7/cli#--json) * [`--lastCommit`](https://jestjs.io/docs/29.7/cli#--lastcommit) * [`--listTests`](https://jestjs.io/docs/29.7/cli#--listtests) * [`--logHeapUsage`](https://jestjs.io/docs/29.7/cli#--logheapusage) * [`--maxConcurrency=`](https://jestjs.io/docs/29.7/cli#--maxconcurrencynum) * [`--maxWorkers=|`](https://jestjs.io/docs/29.7/cli#--maxworkersnumstring) * [`--noStackTrace`](https://jestjs.io/docs/29.7/cli#--nostacktrace) * [`--notify`](https://jestjs.io/docs/29.7/cli#--notify) * [`--onlyChanged`](https://jestjs.io/docs/29.7/cli#--onlychanged) * [`--onlyFailures`](https://jestjs.io/docs/29.7/cli#--onlyfailures) * [`--openHandlesTimeout=`](https://jestjs.io/docs/29.7/cli#--openhandlestimeoutmilliseconds) * [`--outputFile=`](https://jestjs.io/docs/29.7/cli#--outputfilefilename) * [`--passWithNoTests`](https://jestjs.io/docs/29.7/cli#--passwithnotests) * [`--projects ... `](https://jestjs.io/docs/29.7/cli#--projects-path1--pathn) * [`--randomize`](https://jestjs.io/docs/29.7/cli#--randomize) * [`--reporters`](https://jestjs.io/docs/29.7/cli#--reporters) * [`--resetMocks`](https://jestjs.io/docs/29.7/cli#--resetmocks) * [`--restoreMocks`](https://jestjs.io/docs/29.7/cli#--restoremocks) * [`--roots`](https://jestjs.io/docs/29.7/cli#--roots) * [`--runInBand`](https://jestjs.io/docs/29.7/cli#--runinband) * [`--runTestsByPath`](https://jestjs.io/docs/29.7/cli#--runtestsbypath) * [`--seed=`](https://jestjs.io/docs/29.7/cli#--seednum) * [`--selectProjects ... `](https://jestjs.io/docs/29.7/cli#--selectprojects-project1--projectn) * [`--setupFilesAfterEnv ... `](https://jestjs.io/docs/29.7/cli#--setupfilesafterenv-path1--pathn) * [`--shard`](https://jestjs.io/docs/29.7/cli#--shard) * [`--showConfig`](https://jestjs.io/docs/29.7/cli#--showconfig) * [`--showSeed`](https://jestjs.io/docs/29.7/cli#--showseed) * [`--silent`](https://jestjs.io/docs/29.7/cli#--silent) * [`--testEnvironmentOptions=`](https://jestjs.io/docs/29.7/cli#--testenvironmentoptionsjson-string) * [`--testLocationInResults`](https://jestjs.io/docs/29.7/cli#--testlocationinresults) * [`--testMatch glob1 ... globN`](https://jestjs.io/docs/29.7/cli#--testmatch-glob1--globn) * [`--testNamePattern=`](https://jestjs.io/docs/29.7/cli#--testnamepatternregex) * [`--testPathIgnorePatterns=|[array]`](https://jestjs.io/docs/29.7/cli#--testpathignorepatternsregexarray) * [`--testPathPattern=`](https://jestjs.io/docs/29.7/cli#--testpathpatternregex) * [`--testRunner=`](https://jestjs.io/docs/29.7/cli#--testrunnerpath) * [`--testSequencer=`](https://jestjs.io/docs/29.7/cli#--testsequencerpath) * [`--testTimeout=`](https://jestjs.io/docs/29.7/cli#--testtimeoutnumber) * [`--updateSnapshot`](https://jestjs.io/docs/29.7/cli#--updatesnapshot) * [`--useStderr`](https://jestjs.io/docs/29.7/cli#--usestderr) * [`--verbose`](https://jestjs.io/docs/29.7/cli#--verbose) * [`--version`](https://jestjs.io/docs/29.7/cli#--version) * [`--watch`](https://jestjs.io/docs/29.7/cli#--watch) * [`--watchAll`](https://jestjs.io/docs/29.7/cli#--watchall) * [`--watchman`](https://jestjs.io/docs/29.7/cli#--watchman) * [`--workerThreads`](https://jestjs.io/docs/29.7/cli#--workerthreads) * * * Reference[​](https://jestjs.io/docs/29.7/cli#reference "Direct link to Reference") ----------------------------------------------------------------------------------- ### `jest `[​](https://jestjs.io/docs/29.7/cli#jest-regexfortestfiles "Direct link to jest-regexfortestfiles") When you run `jest` with an argument, that argument is treated as a regular expression to match against files in your project. It is possible to run test suites by providing a pattern. Only the files that the pattern matches will be picked up and executed. Depending on your terminal, you may need to quote this argument: `jest "my.*(complex)?pattern"`. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. ### `--bail[=]`[​](https://jestjs.io/docs/29.7/cli#--bailn "Direct link to --bailn") Alias: `-b`. Exit the test suite immediately upon `n` number of failing test suite. Defaults to `1`. ### `--cache`[​](https://jestjs.io/docs/29.7/cli#--cache "Direct link to --cache") Whether to use the cache. Defaults to true. Disable the cache using `--no-cache`. caution The cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower. If you want to inspect the cache, use `--showConfig` and look at the `cacheDirectory` value. If you need to clear the cache, use `--clearCache`. ### `--changedFilesWithAncestor`[​](https://jestjs.io/docs/29.7/cli#--changedfileswithancestor "Direct link to --changedfileswithancestor") Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to `--onlyChanged`. ### `--changedSince`[​](https://jestjs.io/docs/29.7/cli#--changedsince "Direct link to --changedsince") Runs tests related to the changes since the provided branch or commit hash. If the current branch has diverged from the given branch, then only changes made locally will be tested. Behaves similarly to `--onlyChanged`. ### `--ci`[​](https://jestjs.io/docs/29.7/cli#--ci "Direct link to --ci") When this option is provided, Jest will assume it is running in a CI environment. This changes the behavior when a new snapshot is encountered. Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with `--updateSnapshot`. ### `--clearCache`[​](https://jestjs.io/docs/29.7/cli#--clearcache "Direct link to --clearcache") Deletes the Jest cache directory and then exits without running tests. Will delete `cacheDirectory` if the option is passed, or Jest's default cache directory. The default cache directory can be found by calling `jest --showConfig`. caution Clearing the cache will reduce performance. ### `--clearMocks`[​](https://jestjs.io/docs/29.7/cli#--clearmocks "Direct link to --clearmocks") Automatically clear mock calls, instances, contexts and results before every test. Equivalent to calling [`jest.clearAllMocks()`](https://jestjs.io/docs/29.7/jest-object#jestclearallmocks) before each test. This does not remove any mock implementation that may have been provided. ### `--collectCoverageFrom=`[​](https://jestjs.io/docs/29.7/cli#--collectcoveragefromglob "Direct link to --collectcoveragefromglob") A glob pattern relative to `rootDir` matching the files that coverage info needs to be collected from. ### `--colors`[​](https://jestjs.io/docs/29.7/cli#--colors "Direct link to --colors") Forces test results output highlighting even if stdout is not a TTY. note Alternatively you can set the environment variable `FORCE_COLOR=true` to forcefully enable or `FORCE_COLOR=false` to disable colorized output. The use of `FORCE_COLOR` overrides all other color support checks. ### `--config=`[​](https://jestjs.io/docs/29.7/cli#--configpath "Direct link to --configpath") Alias: `-c`. The path to a Jest config file specifying how to find and execute tests. If no `rootDir` is set in the config, the directory containing the config file is assumed to be the `rootDir` for the project. This can also be a JSON-encoded value which Jest will use as configuration. ### `--coverage[=]`[​](https://jestjs.io/docs/29.7/cli#--coverageboolean "Direct link to --coverageboolean") Alias: `--collectCoverage`. Indicates that test coverage information should be collected and reported in the output. Optionally pass `` to override option set in configuration. ### `--coverageDirectory=`[​](https://jestjs.io/docs/29.7/cli#--coveragedirectorypath "Direct link to --coveragedirectorypath") The directory where Jest should output its coverage files. ### `--coverageProvider=`[​](https://jestjs.io/docs/29.7/cli#--coverageproviderprovider "Direct link to --coverageproviderprovider") Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. ### `--debug`[​](https://jestjs.io/docs/29.7/cli#--debug "Direct link to --debug") Print debugging info about your Jest config. ### `--detectOpenHandles`[​](https://jestjs.io/docs/29.7/cli#--detectopenhandles "Direct link to --detectopenhandles") Attempt to collect and print open handles preventing Jest from exiting cleanly. Use this in cases where you need to use `--forceExit` in order for Jest to exit to potentially track down the reason. This implies `--runInBand`, making tests run serially. Implemented using [`async_hooks`](https://nodejs.org/api/async_hooks.html) . This option has a significant performance penalty and should only be used for debugging. ### `--env=`[​](https://jestjs.io/docs/29.7/cli#--envenvironment "Direct link to --envenvironment") The test environment used for all tests. This can point to any file or node module. Examples: `jsdom`, `node` or `path/to/my-environment.js`. ### `--errorOnDeprecated`[​](https://jestjs.io/docs/29.7/cli#--errorondeprecated "Direct link to --errorondeprecated") Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process. ### `--expand`[​](https://jestjs.io/docs/29.7/cli#--expand "Direct link to --expand") Alias: `-e`. Use this flag to show full diffs and errors instead of a patch. ### `--filter=`[​](https://jestjs.io/docs/29.7/cli#--filterfile "Direct link to --filterfile") Path to a module exporting a filtering function. This asynchronous function receives a list of test paths which can be manipulated to exclude tests from running by returning an object with shape `{ filtered: Array<{ test: string }> }`. Especially useful when used in conjunction with a testing infrastructure to filter known broken tests, e.g. my-filter.js module.exports = testPaths => { const allowedPaths = testPaths .filter(filteringFunction) .map(test => ({test})); // [{ test: "path1.spec.js" }, { test: "path2.spec.js" }, etc] return { filtered: allowedPaths, };}; ### `--findRelatedTests `[​](https://jestjs.io/docs/29.7/cli#--findrelatedtests-spaceseparatedlistofsourcefiles "Direct link to --findrelatedtests-spaceseparatedlistofsourcefiles") Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with `--coverage` to include a test coverage for the source files, no duplicate `--collectCoverageFrom` arguments needed. ### `--forceExit`[​](https://jestjs.io/docs/29.7/cli#--forceexit "Direct link to --forceexit") Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up. caution This feature is an escape-hatch. If Jest doesn't exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly. You can use `--detectOpenHandles` to help track it down. ### `--help`[​](https://jestjs.io/docs/29.7/cli#--help "Direct link to --help") Show the help information, similar to this page. ### `--ignoreProjects ... `[​](https://jestjs.io/docs/29.7/cli#--ignoreprojects-project1--projectn "Direct link to --ignoreprojects-project1--projectn") Ignore the tests of the specified projects. Jest uses the attribute `displayName` in the configuration to identify each project. If you use this option, you should provide a `displayName` to all your projects. ### `--init`[​](https://jestjs.io/docs/29.7/cli#--init "Direct link to --init") Generate a basic configuration file. Based on your project, Jest will ask you a few questions that will help to generate a `jest.config.js` file with a short description for each option. ### `--injectGlobals`[​](https://jestjs.io/docs/29.7/cli#--injectglobals "Direct link to --injectglobals") Insert Jest's globals (`expect`, `test`, `describe`, `beforeEach` etc.) into the global environment. If you set this to `false`, you should import from `@jest/globals`, e.g. import {expect, jest, test} from '@jest/globals';jest.useFakeTimers();test('some test', () => { expect(Date.now()).toBe(0);}); note This option is only supported using the default `jest-circus` test runner. ### `--json`[​](https://jestjs.io/docs/29.7/cli#--json "Direct link to --json") Prints the test results in JSON. This mode will send all other test output and user messages to stderr. ### `--lastCommit`[​](https://jestjs.io/docs/29.7/cli#--lastcommit "Direct link to --lastcommit") Run all tests affected by file changes in the last commit made. Behaves similarly to `--onlyChanged`. ### `--listTests`[​](https://jestjs.io/docs/29.7/cli#--listtests "Direct link to --listtests") Lists all test files that Jest will run given the arguments, and exits. ### `--logHeapUsage`[​](https://jestjs.io/docs/29.7/cli#--logheapusage "Direct link to --logheapusage") Logs the heap usage after every test. Useful to debug memory leaks. Use together with `--runInBand` and `--expose-gc` in node. ### `--maxConcurrency=`[​](https://jestjs.io/docs/29.7/cli#--maxconcurrencynum "Direct link to --maxconcurrencynum") Prevents Jest from executing more than the specified amount of tests at the same time. Only affects tests that use `test.concurrent`. ### `--maxWorkers=|`[​](https://jestjs.io/docs/29.7/cli#--maxworkersnumstring "Direct link to --maxworkersnumstring") Alias: `-w`. Specifies the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases. For environments with variable CPUs available, you can use percentage based configuration: `--maxWorkers=50%` ### `--noStackTrace`[​](https://jestjs.io/docs/29.7/cli#--nostacktrace "Direct link to --nostacktrace") Disables stack trace in test results output. ### `--notify`[​](https://jestjs.io/docs/29.7/cli#--notify "Direct link to --notify") Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing. ### `--onlyChanged`[​](https://jestjs.io/docs/29.7/cli#--onlychanged "Direct link to --onlychanged") Alias: `-o`. Attempts to identify which tests to run based on which files have changed in the current repository. Only works if you're running tests in a git/hg repository at the moment and requires a static dependency graph (ie. no dynamic requires). ### `--onlyFailures`[​](https://jestjs.io/docs/29.7/cli#--onlyfailures "Direct link to --onlyfailures") Alias: `-f`. Run tests that failed in the previous execution. ### `--openHandlesTimeout=`[​](https://jestjs.io/docs/29.7/cli#--openhandlestimeoutmilliseconds "Direct link to --openhandlestimeoutmilliseconds") When `--detectOpenHandles` and `--forceExit` are _disabled_, Jest will print a warning if the process has not exited cleanly after this number of milliseconds. A value of `0` disables the warning. Defaults to `1000`. ### `--outputFile=`[​](https://jestjs.io/docs/29.7/cli#--outputfilefilename "Direct link to --outputfilefilename") Write test results to a file when the `--json` option is also specified. The returned JSON structure is documented in [testResultsProcessor](https://jestjs.io/docs/29.7/configuration#testresultsprocessor-string) . ### `--passWithNoTests`[​](https://jestjs.io/docs/29.7/cli#--passwithnotests "Direct link to --passwithnotests") Allows the test suite to pass when no files are found. ### `--projects ... `[​](https://jestjs.io/docs/29.7/cli#--projects-path1--pathn "Direct link to --projects-path1--pathn") Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the [`projects`](https://jestjs.io/docs/29.7/configuration#projects-arraystring--projectconfig) configuration option. note If configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. ### `--randomize`[​](https://jestjs.io/docs/29.7/cli#--randomize "Direct link to --randomize") Shuffle the order of the tests within a file. The shuffling is based on the seed. See [`--seed=`](https://jestjs.io/docs/29.7/cli#--seednum) for more info. Seed value is displayed when this option is set. Equivalent to setting the CLI option [`--showSeed`](https://jestjs.io/docs/29.7/cli#--showseed) . jest --randomize --seed 1234 note This option is only supported using the default `jest-circus` test runner. ### `--reporters`[​](https://jestjs.io/docs/29.7/cli#--reporters "Direct link to --reporters") Run tests with specified reporters. [Reporter options](https://jestjs.io/docs/29.7/configuration#reporters-arraymodulename--modulename-options) are not available via CLI. Example with multiple reporters: `jest --reporters="default" --reporters="jest-junit"` ### `--resetMocks`[​](https://jestjs.io/docs/29.7/cli#--resetmocks "Direct link to --resetmocks") Automatically reset mock state before every test. Equivalent to calling [`jest.resetAllMocks()`](https://jestjs.io/docs/29.7/jest-object#jestresetallmocks) before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation. ### `--restoreMocks`[​](https://jestjs.io/docs/29.7/cli#--restoremocks "Direct link to --restoremocks") Automatically restore mock state and implementation before every test. Equivalent to calling [`jest.restoreAllMocks()`](https://jestjs.io/docs/29.7/jest-object#jestrestoreallmocks) before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation. ### `--roots`[​](https://jestjs.io/docs/29.7/cli#--roots "Direct link to --roots") A list of paths to directories that Jest should use to search for files in. ### `--runInBand`[​](https://jestjs.io/docs/29.7/cli#--runinband "Direct link to --runinband") Alias: `-i`. Run all tests serially in the current process, rather than creating a worker pool of child processes that run tests. This can be useful for debugging. ### `--runTestsByPath`[​](https://jestjs.io/docs/29.7/cli#--runtestsbypath "Direct link to --runtestsbypath") Run only the tests that were specified with their exact paths. This avoids converting them into a regular expression and matching it against every single file. For example, given the following file structure: __tests__└── t1.test.js # test└── t2.test.js # test When ran with a pattern, no test is found: jest --runTestsByPath __tests__/t Output: No tests found However, passing an exact path will execute only the given test: jest --runTestsByPath __tests__/t1.test.js Output: PASS __tests__/t1.test.js tip The default regex matching works fine on small runs, but becomes slow if provided with multiple patterns and/or against a lot of tests. This option replaces the regex matching logic and by that optimizes the time it takes Jest to filter specific test files. ### `--seed=`[​](https://jestjs.io/docs/29.7/cli#--seednum "Direct link to --seednum") Sets a seed value that can be retrieved in a test file via [`jest.getSeed()`](https://jestjs.io/docs/29.7/jest-object#jestgetseed) . The seed value must be between `-0x80000000` and `0x7fffffff` inclusive (`-2147483648` (`-(2 ** 31)`) and `2147483647` (`2 ** 31 - 1`) in decimal). jest --seed=1324 tip If this option is not specified Jest will randomly generate the value. You can use the [`--showSeed`](https://jestjs.io/docs/29.7/cli#--showseed) flag to print the seed in the test report summary. Jest uses the seed internally for shuffling the order in which test suites are run. If the [`--randomize`](https://jestjs.io/docs/29.7/cli#--randomize) option is used, the seed is also used for shuffling the order of tests within each `describe` block. When dealing with flaky tests, rerunning with the same seed might help reproduce the failure. ### `--selectProjects ... `[​](https://jestjs.io/docs/29.7/cli#--selectprojects-project1--projectn "Direct link to --selectprojects-project1--projectn") Run the tests of the specified projects. Jest uses the attribute `displayName` in the configuration to identify each project. If you use this option, you should provide a `displayName` to all your projects. ### `--setupFilesAfterEnv ... `[​](https://jestjs.io/docs/29.7/cli#--setupfilesafterenv-path1--pathn "Direct link to --setupfilesafterenv-path1--pathn") A list of paths to modules that run some code to configure or to set up the testing framework before each test. Beware that files imported by the setup scripts will not be mocked during testing. ### `--shard`[​](https://jestjs.io/docs/29.7/cli#--shard "Direct link to --shard") The test suite shard to execute in a format of `(?\d+)/(?\d+)`. `shardIndex` describes which shard to select while `shardCount` controls the number of shards the suite should be split into. `shardIndex` and `shardCount` have to be 1-based, positive numbers, and `shardIndex` has to be lower than or equal to `shardCount`. When `shard` is specified the configured [`testSequencer`](https://jestjs.io/docs/29.7/configuration#testsequencer-string) has to implement a `shard` method. For example, to split the suite into three shards, each running one third of the tests: jest --shard=1/3jest --shard=2/3jest --shard=3/3 ### `--showConfig`[​](https://jestjs.io/docs/29.7/cli#--showconfig "Direct link to --showconfig") Print your Jest config and then exits. ### `--showSeed`[​](https://jestjs.io/docs/29.7/cli#--showseed "Direct link to --showseed") Prints the seed value in the test report summary. See [`--seed=`](https://jestjs.io/docs/29.7/cli#--seednum) for the details. Can also be set in configuration. See [`showSeed`](https://jestjs.io/docs/29.7/configuration#showseed-boolean) . ### `--silent`[​](https://jestjs.io/docs/29.7/cli#--silent "Direct link to --silent") Prevent tests from printing messages through the console. ### `--testEnvironmentOptions=`[​](https://jestjs.io/docs/29.7/cli#--testenvironmentoptionsjson-string "Direct link to --testenvironmentoptionsjson-string") A JSON string with options that will be passed to the `testEnvironment`. The relevant options depend on the environment. ### `--testLocationInResults`[​](https://jestjs.io/docs/29.7/cli#--testlocationinresults "Direct link to --testlocationinresults") Adds a `location` field to test results. Useful if you want to report the location of a test in a reporter. note In the resulting object `column` is 0-indexed while `line` is not. { "column": 4, "line": 5} ### `--testMatch glob1 ... globN`[​](https://jestjs.io/docs/29.7/cli#--testmatch-glob1--globn "Direct link to --testmatch-glob1--globn") The glob patterns Jest uses to detect test files. Please refer to the [`testMatch` configuration](https://jestjs.io/docs/29.7/configuration#testmatch-arraystring) for details. ### `--testNamePattern=`[​](https://jestjs.io/docs/29.7/cli#--testnamepatternregex "Direct link to --testnamepatternregex") Alias: `-t`. Run only tests with a name that matches the regex. For example, suppose you want to run only tests related to authorization which will have names like `'GET /api/posts with auth'`, then you can use `jest -t=auth`. tip The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks. ### `--testPathIgnorePatterns=|[array]`[​](https://jestjs.io/docs/29.7/cli#--testpathignorepatternsregexarray "Direct link to --testpathignorepatternsregexarray") A single or array of regexp pattern strings that are tested against all tests paths before executing the test. Contrary to `--testPathPattern`, it will only run those tests with a path that does not match with the provided regexp expressions. To pass as an array use escaped parentheses and space delimited regexps such as `\(/node_modules/ /tests/e2e/\)`. Alternatively, you can omit parentheses by combining regexps into a single regexp like `/node_modules/|/tests/e2e/`. These two examples are equivalent. ### `--testPathPattern=`[​](https://jestjs.io/docs/29.7/cli#--testpathpatternregex "Direct link to --testpathpatternregex") A regexp pattern string that is matched against all tests paths before executing the test. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. ### `--testRunner=`[​](https://jestjs.io/docs/29.7/cli#--testrunnerpath "Direct link to --testrunnerpath") Lets you specify a custom test runner. ### `--testSequencer=`[​](https://jestjs.io/docs/29.7/cli#--testsequencerpath "Direct link to --testsequencerpath") Lets you specify a custom test sequencer. Please refer to the [`testSequencer` configuration](https://jestjs.io/docs/29.7/configuration#testsequencer-string) for details. ### `--testTimeout=`[​](https://jestjs.io/docs/29.7/cli#--testtimeoutnumber "Direct link to --testtimeoutnumber") Default timeout of a test in milliseconds. Default value: 5000. ### `--updateSnapshot`[​](https://jestjs.io/docs/29.7/cli#--updatesnapshot "Direct link to --updatesnapshot") Alias: `-u`. Use this flag to re-record every snapshot that fails during this test run. Can be used together with a test suite pattern or with `--testNamePattern` to re-record snapshots. ### `--useStderr`[​](https://jestjs.io/docs/29.7/cli#--usestderr "Direct link to --usestderr") Divert all output to stderr. ### `--verbose`[​](https://jestjs.io/docs/29.7/cli#--verbose "Direct link to --verbose") Display individual test results with the test suite hierarchy. ### `--version`[​](https://jestjs.io/docs/29.7/cli#--version "Direct link to --version") Alias: `-v`. Print the version and exit. ### `--watch`[​](https://jestjs.io/docs/29.7/cli#--watch "Direct link to --watch") Watch files for changes and rerun tests related to changed files. If you want to re-run all tests when a file has changed, use the `--watchAll` option instead. tip Use `--no-watch` (or `--watch=false`) to explicitly disable the watch mode if it was enabled using `--watch`. In most CI environments, this is automatically handled for you. ### `--watchAll`[​](https://jestjs.io/docs/29.7/cli#--watchall "Direct link to --watchall") Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the `--watch` option. tip Use `--no-watchAll` (or `--watchAll=false`) to explicitly disable the watch mode if it was enabled using `--watchAll`. In most CI environments, this is automatically handled for you. ### `--watchman`[​](https://jestjs.io/docs/29.7/cli#--watchman "Direct link to --watchman") Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawling. Defaults to `true`. Disable using `--no-watchman`. ### `--workerThreads`[​](https://jestjs.io/docs/29.7/cli#--workerthreads "Direct link to --workerthreads") Whether to use [worker threads](https://nodejs.org/dist/latest/docs/api/worker_threads.html) for parallelization. [Child processes](https://nodejs.org/dist/latest/docs/api/child_process.html) are used by default. caution This is **experimental feature**. See the [`workerThreads` configuration option](https://jestjs.io/docs/29.7/configuration#workerthreads) for more details. * [Running from the command line](https://jestjs.io/docs/29.7/cli#running-from-the-command-line) * [Using with package manager](https://jestjs.io/docs/29.7/cli#using-with-package-manager) * [Camelcase & dashed args support](https://jestjs.io/docs/29.7/cli#camelcase--dashed-args-support) * [Options](https://jestjs.io/docs/29.7/cli#options) * [Reference](https://jestjs.io/docs/29.7/cli#reference) * [`jest `](https://jestjs.io/docs/29.7/cli#jest-regexfortestfiles) * [`--bail[=]`](https://jestjs.io/docs/29.7/cli#--bailn) * [`--cache`](https://jestjs.io/docs/29.7/cli#--cache) * [`--changedFilesWithAncestor`](https://jestjs.io/docs/29.7/cli#--changedfileswithancestor) * [`--changedSince`](https://jestjs.io/docs/29.7/cli#--changedsince) * [`--ci`](https://jestjs.io/docs/29.7/cli#--ci) * [`--clearCache`](https://jestjs.io/docs/29.7/cli#--clearcache) * [`--clearMocks`](https://jestjs.io/docs/29.7/cli#--clearmocks) * [`--collectCoverageFrom=`](https://jestjs.io/docs/29.7/cli#--collectcoveragefromglob) * [`--colors`](https://jestjs.io/docs/29.7/cli#--colors) * [`--config=`](https://jestjs.io/docs/29.7/cli#--configpath) * [`--coverage[=]`](https://jestjs.io/docs/29.7/cli#--coverageboolean) * [`--coverageDirectory=`](https://jestjs.io/docs/29.7/cli#--coveragedirectorypath) * [`--coverageProvider=`](https://jestjs.io/docs/29.7/cli#--coverageproviderprovider) * [`--debug`](https://jestjs.io/docs/29.7/cli#--debug) * [`--detectOpenHandles`](https://jestjs.io/docs/29.7/cli#--detectopenhandles) * [`--env=`](https://jestjs.io/docs/29.7/cli#--envenvironment) * [`--errorOnDeprecated`](https://jestjs.io/docs/29.7/cli#--errorondeprecated) * [`--expand`](https://jestjs.io/docs/29.7/cli#--expand) * [`--filter=`](https://jestjs.io/docs/29.7/cli#--filterfile) * [`--findRelatedTests `](https://jestjs.io/docs/29.7/cli#--findrelatedtests-spaceseparatedlistofsourcefiles) * [`--forceExit`](https://jestjs.io/docs/29.7/cli#--forceexit) * [`--help`](https://jestjs.io/docs/29.7/cli#--help) * [`--ignoreProjects ... `](https://jestjs.io/docs/29.7/cli#--ignoreprojects-project1--projectn) * [`--init`](https://jestjs.io/docs/29.7/cli#--init) * [`--injectGlobals`](https://jestjs.io/docs/29.7/cli#--injectglobals) * [`--json`](https://jestjs.io/docs/29.7/cli#--json) * [`--lastCommit`](https://jestjs.io/docs/29.7/cli#--lastcommit) * [`--listTests`](https://jestjs.io/docs/29.7/cli#--listtests) * [`--logHeapUsage`](https://jestjs.io/docs/29.7/cli#--logheapusage) * [`--maxConcurrency=`](https://jestjs.io/docs/29.7/cli#--maxconcurrencynum) * [`--maxWorkers=|`](https://jestjs.io/docs/29.7/cli#--maxworkersnumstring) * [`--noStackTrace`](https://jestjs.io/docs/29.7/cli#--nostacktrace) * [`--notify`](https://jestjs.io/docs/29.7/cli#--notify) * [`--onlyChanged`](https://jestjs.io/docs/29.7/cli#--onlychanged) * [`--onlyFailures`](https://jestjs.io/docs/29.7/cli#--onlyfailures) * [`--openHandlesTimeout=`](https://jestjs.io/docs/29.7/cli#--openhandlestimeoutmilliseconds) * [`--outputFile=`](https://jestjs.io/docs/29.7/cli#--outputfilefilename) * [`--passWithNoTests`](https://jestjs.io/docs/29.7/cli#--passwithnotests) * [`--projects ... `](https://jestjs.io/docs/29.7/cli#--projects-path1--pathn) * [`--randomize`](https://jestjs.io/docs/29.7/cli#--randomize) * [`--reporters`](https://jestjs.io/docs/29.7/cli#--reporters) * [`--resetMocks`](https://jestjs.io/docs/29.7/cli#--resetmocks) * [`--restoreMocks`](https://jestjs.io/docs/29.7/cli#--restoremocks) * [`--roots`](https://jestjs.io/docs/29.7/cli#--roots) * [`--runInBand`](https://jestjs.io/docs/29.7/cli#--runinband) * [`--runTestsByPath`](https://jestjs.io/docs/29.7/cli#--runtestsbypath) * [`--seed=`](https://jestjs.io/docs/29.7/cli#--seednum) * [`--selectProjects ... `](https://jestjs.io/docs/29.7/cli#--selectprojects-project1--projectn) * [`--setupFilesAfterEnv ... `](https://jestjs.io/docs/29.7/cli#--setupfilesafterenv-path1--pathn) * [`--shard`](https://jestjs.io/docs/29.7/cli#--shard) * [`--showConfig`](https://jestjs.io/docs/29.7/cli#--showconfig) * [`--showSeed`](https://jestjs.io/docs/29.7/cli#--showseed) * [`--silent`](https://jestjs.io/docs/29.7/cli#--silent) * [`--testEnvironmentOptions=`](https://jestjs.io/docs/29.7/cli#--testenvironmentoptionsjson-string) * [`--testLocationInResults`](https://jestjs.io/docs/29.7/cli#--testlocationinresults) * [`--testMatch glob1 ... globN`](https://jestjs.io/docs/29.7/cli#--testmatch-glob1--globn) * [`--testNamePattern=`](https://jestjs.io/docs/29.7/cli#--testnamepatternregex) * [`--testPathIgnorePatterns=|[array]`](https://jestjs.io/docs/29.7/cli#--testpathignorepatternsregexarray) * [`--testPathPattern=`](https://jestjs.io/docs/29.7/cli#--testpathpatternregex) * [`--testRunner=`](https://jestjs.io/docs/29.7/cli#--testrunnerpath) * [`--testSequencer=`](https://jestjs.io/docs/29.7/cli#--testsequencerpath) * [`--testTimeout=`](https://jestjs.io/docs/29.7/cli#--testtimeoutnumber) * [`--updateSnapshot`](https://jestjs.io/docs/29.7/cli#--updatesnapshot) * [`--useStderr`](https://jestjs.io/docs/29.7/cli#--usestderr) * [`--verbose`](https://jestjs.io/docs/29.7/cli#--verbose) * [`--version`](https://jestjs.io/docs/29.7/cli#--version) * [`--watch`](https://jestjs.io/docs/29.7/cli#--watch) * [`--watchAll`](https://jestjs.io/docs/29.7/cli#--watchall) * [`--watchman`](https://jestjs.io/docs/29.7/cli#--watchman) * [`--workerThreads`](https://jestjs.io/docs/29.7/cli#--workerthreads) --- # Jest Community · Jest [Skip to main content](https://jestjs.io/docs/29.7/jest-community#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/jest-community) ** (30.0). Version: 29.7 On this page The community around Jest is working hard to make the testing experience even greater. [jest-community](https://github.com/jest-community) is a new GitHub organization for high quality Jest additions curated by Jest maintainers and collaborators. It already features some of our favorite projects, to name a few: * [vscode-jest](https://github.com/jest-community/vscode-jest) * [jest-extended](https://github.com/jest-community/jest-extended) * [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) * [awesome-jest](https://github.com/jest-community/awesome-jest) Community projects under one organization are a great way for Jest to experiment with new ideas/techniques and approaches. Encourage contributions from the community and publish contributions independently at a faster pace. Awesome Jest[​](https://jestjs.io/docs/29.7/jest-community#awesome-jest "Direct link to Awesome Jest") ------------------------------------------------------------------------------------------------------- The jest-community org maintains an [awesome-jest](https://github.com/jest-community/awesome-jest) list of great projects and resources related to Jest. If you have something awesome to share, feel free to reach out to us! We'd love to share your project on the awesome-jest list ([send a PR here](https://github.com/jest-community/awesome-jest/pulls) ) or if you would like to transfer your project to the jest-community org reach out to one of the owners of the org. * [Awesome Jest](https://jestjs.io/docs/29.7/jest-community#awesome-jest) --- # Architecture · Jest [Skip to main content](https://jestjs.io/docs/29.7/architecture#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/architecture) ** (30.0). Version: 29.7 If you are interested in learning more about how Jest works, understand its architecture, and how Jest is split up into individual reusable packages, check out this video: If you'd like to learn how to build a testing framework like Jest from scratch, check out this video: There is also a [written guide you can follow](https://cpojer.net/posts/building-a-javascript-testing-framework) . It teaches the fundamental concepts of Jest and explains how various parts of Jest can be used to compose a custom testing framework. --- # Testing Web Frameworks · Jest [Skip to main content](https://jestjs.io/docs/29.7/testing-frameworks#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/testing-frameworks) ** (30.0). Version: 29.7 On this page Jest is a universal testing platform, with the ability to adapt to any JavaScript library or framework. In this section, we'd like to link to community posts and articles about integrating Jest into popular JS libraries. React[​](https://jestjs.io/docs/29.7/testing-frameworks#react "Direct link to React") -------------------------------------------------------------------------------------- * [Testing ReactJS components with Jest](https://testing-library.com/docs/react-testing-library/example-intro) by Kent C. Dodds ([@kentcdodds](https://twitter.com/kentcdodds) ) Vue.js[​](https://jestjs.io/docs/29.7/testing-frameworks#vuejs "Direct link to Vue.js") ---------------------------------------------------------------------------------------- * [Testing Vue.js components with Jest](https://alexjoverm.github.io/series/Unit-Testing-Vue-js-Components-with-the-Official-Vue-Testing-Tools-and-Jest/) by Alex Jover Morales ([@alexjoverm](https://twitter.com/alexjoverm) ) * [Jest for all: Episode 1 — Vue.js](https://medium.com/@kentaromiura_the_js_guy/jest-for-all-episode-1-vue-js-d616bccbe186#.d573vrce2) by Cristian Carlesso ([@kentaromiura](https://twitter.com/kentaromiura) ) AngularJS[​](https://jestjs.io/docs/29.7/testing-frameworks#angularjs "Direct link to AngularJS") -------------------------------------------------------------------------------------------------- * [Testing an AngularJS app with Jest](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251) by Matthieu Lux ([@Swiip](https://twitter.com/Swiip) ) * [Running AngularJS Tests with Jest](https://benjaminbrandt.com/running-angularjs-tests-with-jest/) by Ben Brandt ([@benjaminbrandt](https://twitter.com/benjaminbrandt) ) * [AngularJS Unit Tests with Jest Actions (Traditional Chinese)](https://dwatow.github.io/2019/08-14-angularjs/angular-jest/?fbclid=IwAR2SrqYg_o6uvCQ79FdNPeOxs86dUqB6pPKgd9BgnHt1kuIDRyRM-ch11xg) by Chris Wang ([@dwatow](https://github.com/dwatow) ) Angular[​](https://jestjs.io/docs/29.7/testing-frameworks#angular "Direct link to Angular") -------------------------------------------------------------------------------------------- * [Testing Angular faster with Jest](https://www.xfive.co/blog/testing-angular-faster-jest/) by Michał Pierzchała ([@thymikee](https://twitter.com/thymikee) ) MobX[​](https://jestjs.io/docs/29.7/testing-frameworks#mobx "Direct link to MobX") ----------------------------------------------------------------------------------- * [How to Test React and MobX with Jest](https://semaphoreci.com/community/tutorials/how-to-test-react-and-mobx-with-jest) by Will Stern ([@willsterndev](https://twitter.com/willsterndev) ) Redux[​](https://jestjs.io/docs/29.7/testing-frameworks#redux "Direct link to Redux") -------------------------------------------------------------------------------------- * [Writing Tests](https://redux.js.org/recipes/writing-tests) by Redux docs Express.js[​](https://jestjs.io/docs/29.7/testing-frameworks#expressjs "Direct link to Express.js") ---------------------------------------------------------------------------------------------------- * [How to test Express.js with Jest and Supertest](https://www.albertgao.com/2017/05/24/how-to-test-expressjs-with-jest-and-supertest/) by Albert Gao ([@albertgao](https://twitter.com/albertgao) ) GatsbyJS[​](https://jestjs.io/docs/29.7/testing-frameworks#gatsbyjs "Direct link to GatsbyJS") ----------------------------------------------------------------------------------------------- * [Unit Testing](https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/) by GatsbyJS docs Hapi.js[​](https://jestjs.io/docs/29.7/testing-frameworks#hapijs "Direct link to Hapi.js") ------------------------------------------------------------------------------------------- * [Testing Hapi.js With Jest](https://github.com/sivasankars/testing-hapi.js-with-jest) by Niralar Next.js[​](https://jestjs.io/docs/29.7/testing-frameworks#nextjs "Direct link to Next.js") ------------------------------------------------------------------------------------------- * [Jest and React Testing Library](https://nextjs.org/docs/pages/building-your-application/testing/jest) by Next.js docs NestJS[​](https://jestjs.io/docs/29.7/testing-frameworks#nestjs "Direct link to NestJS") ----------------------------------------------------------------------------------------- * [Jest and NestJS dependencies](https://docs.nestjs.com/fundamentals/testing#unit-testing) by NestJS docs * [React](https://jestjs.io/docs/29.7/testing-frameworks#react) * [Vue.js](https://jestjs.io/docs/29.7/testing-frameworks#vuejs) * [AngularJS](https://jestjs.io/docs/29.7/testing-frameworks#angularjs) * [Angular](https://jestjs.io/docs/29.7/testing-frameworks#angular) * [MobX](https://jestjs.io/docs/29.7/testing-frameworks#mobx) * [Redux](https://jestjs.io/docs/29.7/testing-frameworks#redux) * [Express.js](https://jestjs.io/docs/29.7/testing-frameworks#expressjs) * [GatsbyJS](https://jestjs.io/docs/29.7/testing-frameworks#gatsbyjs) * [Hapi.js](https://jestjs.io/docs/29.7/testing-frameworks#hapijs) * [Next.js](https://jestjs.io/docs/29.7/testing-frameworks#nextjs) * [NestJS](https://jestjs.io/docs/29.7/testing-frameworks#nestjs) --- # From v28 to v29 · Jest [Skip to main content](https://jestjs.io/docs/29.7/upgrading-to-jest29#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/upgrading-to-jest29) ** (30.0). Version: 29.7 On this page Upgrading Jest from v28 to v29? This guide aims to help refactoring your configuration and tests. info See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. note Upgrading from an older version? You can see the upgrade guide from v27 to v28 [here](https://jest-archive-august-2023.netlify.app/docs/28.x/upgrading-to-jest28) . Compatibility[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#compatibility "Direct link to Compatibility") --------------------------------------------------------------------------------------------------------------- The supported Node versions are 14.15, 16.10, 18.0 and above. Snapshot format[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#snapshot-format "Direct link to Snapshot format") --------------------------------------------------------------------------------------------------------------------- As announced in the [Jest 28 blog post](https://jestjs.io/blog/2022/04/25/jest-28#future) , Jest 29 has changed the default snapshot formatting to `{escapeString: false, printBasicPrototype: false}`. If you want to keep the old behavior, you can set the `snapshotFormat` property to: + snapshotFormat: {+ escapeString: true,+ printBasicPrototype: true+ } JSDOM upgrade[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#jsdom-upgrade "Direct link to JSDOM upgrade") --------------------------------------------------------------------------------------------------------------- `jest-environment-jsdom` has upgraded `jsdom` from v19 to v20. info If you use `jest-environment-jsdom`, the minimum TypeScript version is set to `4.5`. Notably, `jsdom@20` includes support for `crypto.getRandomValues()`, which means packages like `uuid` and `nanoid`, which doesn't work properly in Jest@28, can work without extra polyfills. `pretty-format`[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#pretty-format "Direct link to pretty-format") ----------------------------------------------------------------------------------------------------------------- `ConvertAnsi` plugin is removed from `pretty-format` package in favour of [`jest-serializer-ansi-escapes`](https://github.com/mrazauskas/jest-serializer-ansi-escapes) . ### `jest-mock`[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#jest-mock "Direct link to jest-mock") Exports of `Mocked*` utility types from `jest-mock` package have changed. `MaybeMockedDeep` and `MaybeMocked` now are exported as `Mocked` and `MockedShallow` respectively; only deep mocked variants of `MockedClass`, `MockedFunction` and `MockedObject` are exposed. TypeScript[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#typescript "Direct link to TypeScript") ------------------------------------------------------------------------------------------------------ info The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs: import {expect, jest, test} from '@jest/globals'; Consult the [Getting Started](https://jestjs.io/docs/29.7/getting-started#using-typescript) guide for details on how to setup Jest with TypeScript. ### `jest.mocked()`[​](https://jestjs.io/docs/29.7/upgrading-to-jest29#jestmocked "Direct link to jestmocked") The [`jest.mocked()`](https://jestjs.io/docs/29.7/mock-function-api#jestmockedsource-options) helper method now wraps types of deep members of passed object by default. If you have used the method with `true` as the second argument, remove it to avoid type errors: - const mockedObject = jest.mocked(someObject, true);+ const mockedObject = jest.mocked(someObject); To have the old shallow mocked behavior, pass `{shallow: true}` as the second argument: - const mockedObject = jest.mocked(someObject);+ const mockedObject = jest.mocked(someObject, {shallow: true}); * [Compatibility](https://jestjs.io/docs/29.7/upgrading-to-jest29#compatibility) * [Snapshot format](https://jestjs.io/docs/29.7/upgrading-to-jest29#snapshot-format) * [JSDOM upgrade](https://jestjs.io/docs/29.7/upgrading-to-jest29#jsdom-upgrade) * [`pretty-format`](https://jestjs.io/docs/29.7/upgrading-to-jest29#pretty-format) * [`jest-mock`](https://jestjs.io/docs/29.7/upgrading-to-jest29#jest-mock) * [TypeScript](https://jestjs.io/docs/29.7/upgrading-to-jest29#typescript) * [`jest.mocked()`](https://jestjs.io/docs/29.7/upgrading-to-jest29#jestmocked) --- # Bypassing module mocks · Jest [Skip to main content](https://jestjs.io/docs/29.7/bypassing-module-mocks#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/bypassing-module-mocks) ** (30.0). Version: 29.7 Jest allows you to mock out whole modules in your tests, which can be useful for testing if your code is calling functions from that module correctly. However, sometimes you may want to use parts of a mocked module in your _test file_, in which case you want to access the original implementation, rather than a mocked version. Consider writing a test case for this `createUser` function: createUser.js import fetch from 'node-fetch';export const createUser = async () => { const response = await fetch('https://website.com/users', {method: 'POST'}); const userId = await response.text(); return userId;}; Your test will want to mock the `fetch` function so that we can be sure that it gets called without actually making the network request. However, you'll also need to mock the return value of `fetch` with a `Response` (wrapped in a `Promise`), as our function uses it to grab the created user's ID. So you might initially try writing a test like this: jest.mock('node-fetch');import fetch, {Response} from 'node-fetch';import {createUser} from './createUser';test('createUser calls fetch with the right args and returns the user id', async () => { fetch.mockReturnValue(Promise.resolve(new Response('4'))); const userId = await createUser(); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith('https://website.com/users', { method: 'POST', }); expect(userId).toBe('4');}); However, if you ran that test you would find that the `createUser` function would fail, throwing the error: `TypeError: response.text is not a function`. This is because the `Response` class you've imported from `node-fetch` has been mocked (due to the `jest.mock` call at the top of the test file) so it no longer behaves the way it should. To get around problems like this, Jest provides the `jest.requireActual` helper. To make the above test work, make the following change to the imports in the test file: // BEFOREjest.mock('node-fetch');import fetch, {Response} from 'node-fetch'; // AFTERjest.mock('node-fetch');import fetch from 'node-fetch';const {Response} = jest.requireActual('node-fetch'); This allows your test file to import the actual `Response` object from `node-fetch`, rather than a mocked version. This means the test will now pass correctly. --- # Using with DynamoDB · Jest [Skip to main content](https://jestjs.io/docs/29.7/dynamodb#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/dynamodb) ** (30.0). Version: 29.7 On this page With the [Global Setup/Teardown](https://jestjs.io/docs/29.7/configuration#globalsetup-string) and [Async Test Environment](https://jestjs.io/docs/29.7/configuration#testenvironment-string) APIs, Jest can work smoothly with [DynamoDB](https://aws.amazon.com/dynamodb/) . Use jest-dynamodb Preset[​](https://jestjs.io/docs/29.7/dynamodb#use-jest-dynamodb-preset "Direct link to Use jest-dynamodb Preset") ------------------------------------------------------------------------------------------------------------------------------------- [Jest DynamoDB](https://github.com/shelfio/jest-dynamodb) provides all required configuration to run your tests using DynamoDB. 1. First, install `@shelf/jest-dynamodb` * npm * Yarn * pnpm npm install --save-dev @shelf/jest-dynamodb yarn add --dev @shelf/jest-dynamodb pnpm add --save-dev @shelf/jest-dynamodb 2. Specify preset in your Jest configuration: { "preset": "@shelf/jest-dynamodb"} 3. Create `jest-dynamodb-config.js` and define DynamoDB tables See [Create Table API](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property) module.exports = { tables: [ { TableName: `files`, KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}], AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}], ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1}, }, // etc ],}; 4. Configure DynamoDB client const {DocumentClient} = require('aws-sdk/clients/dynamodb');const isTest = process.env.JEST_WORKER_ID;const config = { convertEmptyValues: true, ...(isTest && { endpoint: 'localhost:8000', sslEnabled: false, region: 'local-env', }),};const ddb = new DocumentClient(config); 5. Write tests it('should insert item into table', async () => { await ddb .put({TableName: 'files', Item: {id: '1', hello: 'world'}}) .promise(); const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise(); expect(Item).toEqual({ id: '1', hello: 'world', });}); There's no need to load any dependencies. See [documentation](https://github.com/shelfio/jest-dynamodb) for details. * [Use jest-dynamodb Preset](https://jestjs.io/docs/29.7/dynamodb#use-jest-dynamodb-preset) --- # Globals · Jest [Skip to main content](https://jestjs.io/docs/29.7/api#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/api) ** (30.0). Version: 29.7 On this page 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, test} from '@jest/globals'`. info The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs: import {expect, jest, test} from '@jest/globals'; Consult the [Getting Started](https://jestjs.io/docs/29.7/getting-started#using-typescript) guide for details on how to setup Jest with TypeScript. Methods[​](https://jestjs.io/docs/29.7/api#methods "Direct link to Methods") ----------------------------------------------------------------------------- * [Reference](https://jestjs.io/docs/29.7/api#reference) * [`afterAll(fn, timeout)`](https://jestjs.io/docs/29.7/api#afterallfn-timeout) * [`afterEach(fn, timeout)`](https://jestjs.io/docs/29.7/api#aftereachfn-timeout) * [`beforeAll(fn, timeout)`](https://jestjs.io/docs/29.7/api#beforeallfn-timeout) * [`beforeEach(fn, timeout)`](https://jestjs.io/docs/29.7/api#beforeeachfn-timeout) * [`describe(name, fn)`](https://jestjs.io/docs/29.7/api#describename-fn) * [`describe.each(table)(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#describeeachtablename-fn-timeout) * [`describe.only(name, fn)`](https://jestjs.io/docs/29.7/api#describeonlyname-fn) * [`describe.only.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#describeonlyeachtablename-fn) * [`describe.skip(name, fn)`](https://jestjs.io/docs/29.7/api#describeskipname-fn) * [`describe.skip.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#describeskipeachtablename-fn) * [`test(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testname-fn-timeout) * [`test.concurrent(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testconcurrentname-fn-timeout) * [`test.concurrent.each(table)(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testconcurrenteachtablename-fn-timeout) * [`test.concurrent.only.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testconcurrentonlyeachtablename-fn) * [`test.concurrent.skip.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testconcurrentskipeachtablename-fn) * [`test.each(table)(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testeachtablename-fn-timeout) * [`test.failing(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testfailingname-fn-timeout) * [`test.failing.each(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testfailingeachname-fn-timeout) * [`test.only.failing(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testonlyfailingname-fn-timeout) * [`test.skip.failing(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testskipfailingname-fn-timeout) * [`test.only(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testonlyname-fn-timeout) * [`test.only.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testonlyeachtablename-fn-1) * [`test.skip(name, fn)`](https://jestjs.io/docs/29.7/api#testskipname-fn) * [`test.skip.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testskipeachtablename-fn) * [`test.todo(name)`](https://jestjs.io/docs/29.7/api#testtodoname) * [TypeScript Usage](https://jestjs.io/docs/29.7/api#typescript-usage) * [`.each`](https://jestjs.io/docs/29.7/api#each) * * * Reference[​](https://jestjs.io/docs/29.7/api#reference "Direct link to Reference") ----------------------------------------------------------------------------------- ### `afterAll(fn, timeout)`[​](https://jestjs.io/docs/29.7/api#afterallfn-timeout "Direct link to afterallfn-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. 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: 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)`[​](https://jestjs.io/docs/29.7/api#aftereachfn-timeout "Direct link to aftereachfn-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. 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: 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)`[​](https://jestjs.io/docs/29.7/api#beforeallfn-timeout "Direct link to beforeallfn-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. 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: 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)`[​](https://jestjs.io/docs/29.7/api#beforeeachfn-timeout "Direct link to beforeeachfn-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. 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: 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)`[​](https://jestjs.io/docs/29.7/api#describename-fn "Direct link to describename-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: 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: 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')).toThrow(CustomError); }); test('with extra whitespace throws CustomError', () => { expect(() => binaryStringToNumber(' 100')).toThrow(CustomError); }); }); describe('given a valid binary string', () => { test('returns the correct number', () => { expect(binaryStringToNumber('100')).toBe(4); }); });}); ### `describe.each(table)(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#describeeachtablename-fn-timeout "Direct link to describeeachtablename-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)`[​](https://jestjs.io/docs/29.7/api#1-describeeachtablename-fn-timeout "Direct link to 1-describeeachtablename-fn-timeout") * `table`: `Array` of Arrays with the arguments that are passed into the `fn` for each row. 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. * Or generate unique test titles by injecting properties of test case object with `$variable` * To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` (only works for ["own" properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) , e.g. `$variable.constructor.name` wouldn't work) * You can use `$#` to inject the index of the test case * You cannot use `$variable` with the `printf` formatting except for `%%` * `fn`: `Function` the suite of tests to be run, 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. The default timeout is 5 seconds. Example: 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); });}); describe.each([ {a: 1, b: 1, expected: 2}, {a: 1, b: 2, expected: 3}, {a: 2, b: 1, expected: 3},])('.add($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); });}); #### 2\. ``describe.each`table`(name, fn, timeout)``[​](https://jestjs.io/docs/29.7/api#2-describeeachtablename-fn-timeout "Direct link to 2-describeeachtablename-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, and `$#` for the index of the row. * To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` (only works for ["own" properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) , e.g. `$variable.constructor.name` wouldn't work) * `fn`: `Function` the suite of tests to be run, 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. The default timeout is 5 seconds. Example: 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)`[​](https://jestjs.io/docs/29.7/api#describeonlyname-fn "Direct link to describeonlyname-fn") Also under the alias: `fdescribe(name, fn)` You can use `describe.only` if you want to run only one describe block: 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)`[​](https://jestjs.io/docs/29.7/api#describeonlyeachtablename-fn "Direct link to describeonlyeachtablename-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)`[​](https://jestjs.io/docs/29.7/api#describeonlyeachtablename-fn-1 "Direct link to describeonlyeachtablename-fn-1") 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 run', () => { expect(1 / 0).toBe(Infinity);}); #### ``describe.only.each`table`(name, fn)``[​](https://jestjs.io/docs/29.7/api#describeonlyeachtablename-fn-2 "Direct link to describeonlyeachtablename-fn-2") describe.only.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', ({a, b, expected}) => { test('passes', () => { expect(a + b).toBe(expected); });});test('will not be run', () => { expect(1 / 0).toBe(Infinity);}); ### `describe.skip(name, fn)`[​](https://jestjs.io/docs/29.7/api#describeskipname-fn "Direct link to describeskipname-fn") Also under the alias: `xdescribe(name, fn)` You can use `describe.skip` if you do not want to run the tests of a particular `describe` block: 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. Beware that the `describe` block will still run. If you have some setup that also should be skipped, do it in a `beforeAll` or `beforeEach` block. ### `describe.skip.each(table)(name, fn)`[​](https://jestjs.io/docs/29.7/api#describeskipeachtablename-fn "Direct link to describeskipeachtablename-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)`[​](https://jestjs.io/docs/29.7/api#describeskipeachtablename-fn-1 "Direct link to describeskipeachtablename-fn-1") 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 run });});test('will be run', () => { expect(1 / 0).toBe(Infinity);}); #### ``describe.skip.each`table`(name, fn)``[​](https://jestjs.io/docs/29.7/api#describeskipeachtablename-fn-2 "Direct link to describeskipeachtablename-fn-2") describe.skip.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', ({a, b, expected}) => { test('will not be run', () => { expect(a + b).toBe(expected); // will not be run });});test('will be run', () => { expect(1 / 0).toBe(Infinity);}); ### `test(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testname-fn-timeout "Direct link to testname-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: 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. The default timeout is 5 seconds. If a **promise is returned** from `test`, Jest will wait for the promise to resolve before letting the test complete. 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: 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. For more details, see [Testing Asynchronous Code](https://jestjs.io/docs/29.7/asynchronous) page. tip 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](https://jestjs.io/docs/29.7/asynchronous#callbacks) . ### `test.concurrent(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testconcurrentname-fn-timeout "Direct link to testconcurrentname-fn-timeout") Also under the alias: `it.concurrent(name, fn, timeout)` caution `test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. Use `test.concurrent` if you want the test to run concurrently. The first argument is the test name; the second argument is an asynchronous function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. test.concurrent('addition of 2 numbers', async () => { expect(5 + 3).toBe(8);});test.concurrent('subtraction 2 numbers', async () => { expect(5 - 3).toBe(2);}); tip Use the [`maxConcurrency`](https://jestjs.io/docs/29.7/configuration#maxconcurrency-number) configuration option to prevent Jest from executing more than the specified amount of tests at the same time. ### `test.concurrent.each(table)(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testconcurrenteachtablename-fn-timeout "Direct link to testconcurrenteachtablename-fn-timeout") Also under the alias: `it.concurrent.each(table)(name, fn, timeout)` Use `test.concurrent.each` if you keep duplicating the same test with different data. `test.each` allows you to write the test once and pass data in, the tests are all run asynchronously. `test.concurrent.each` is available with two APIs: #### 1\. `test.concurrent.each(table)(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#1-testconcurrenteachtablename-fn-timeout "Direct link to 1-testconcurrenteachtablename-fn-timeout") * `table`: `Array` of Arrays with the arguments that are passed into the test `fn` for each row. 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 run, this is the function that will receive the parameters in each row as function arguments, **this will have to be an asynchronous function**. * Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. Example: test.concurrent.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3],])('.add(%i, %i)', async (a, b, expected) => { expect(a + b).toBe(expected);}); #### 2\. ``test.concurrent.each`table`(name, fn, timeout)``[​](https://jestjs.io/docs/29.7/api#2-testconcurrenteachtablename-fn-timeout "Direct link to 2-testconcurrenteachtablename-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` (only works for ["own" properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) , e.g. `$variable.constructor.name` wouldn't work) * `fn`: `Function` the test to be run, this is the function that will receive the test data object, **this will have to be an asynchronous function**. * Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. Example: test.concurrent.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', async ({a, b, expected}) => { expect(a + b).toBe(expected);}); ### `test.concurrent.only.each(table)(name, fn)`[​](https://jestjs.io/docs/29.7/api#testconcurrentonlyeachtablename-fn "Direct link to testconcurrentonlyeachtablename-fn") Also under the alias: `it.concurrent.only.each(table)(name, fn)` Use `test.concurrent.only.each` if you want to only run specific tests with different test data concurrently. `test.concurrent.only.each` is available with two APIs: #### `test.concurrent.only.each(table)(name, fn)`[​](https://jestjs.io/docs/29.7/api#testconcurrentonlyeachtablename-fn-1 "Direct link to testconcurrentonlyeachtablename-fn-1") test.concurrent.only.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3],])('.add(%i, %i)', async (a, b, expected) => { expect(a + b).toBe(expected);});test('will not be run', () => { expect(1 / 0).toBe(Infinity);}); #### ``test.only.each`table`(name, fn)``[​](https://jestjs.io/docs/29.7/api#testonlyeachtablename-fn "Direct link to testonlyeachtablename-fn") test.concurrent.only.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', async ({a, b, expected}) => { expect(a + b).toBe(expected);});test('will not be run', () => { expect(1 / 0).toBe(Infinity);}); ### `test.concurrent.skip.each(table)(name, fn)`[​](https://jestjs.io/docs/29.7/api#testconcurrentskipeachtablename-fn "Direct link to testconcurrentskipeachtablename-fn") Also under the alias: `it.concurrent.skip.each(table)(name, fn)` Use `test.concurrent.skip.each` if you want to stop running a collection of asynchronous data driven tests. `test.concurrent.skip.each` is available with two APIs: #### `test.concurrent.skip.each(table)(name, fn)`[​](https://jestjs.io/docs/29.7/api#testconcurrentskipeachtablename-fn-1 "Direct link to testconcurrentskipeachtablename-fn-1") test.concurrent.skip.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3],])('.add(%i, %i)', async (a, b, expected) => { expect(a + b).toBe(expected); // will not be run});test('will be run', () => { expect(1 / 0).toBe(Infinity);}); #### ``test.concurrent.skip.each`table`(name, fn)``[​](https://jestjs.io/docs/29.7/api#testconcurrentskipeachtablename-fn-2 "Direct link to testconcurrentskipeachtablename-fn-2") test.concurrent.skip.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', async ({a, b, expected}) => { expect(a + b).toBe(expected); // will not be run});test('will be run', () => { expect(1 / 0).toBe(Infinity);}); ### `test.each(table)(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testeachtablename-fn-timeout "Direct link to testeachtablename-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)`[​](https://jestjs.io/docs/29.7/api#1-testeachtablename-fn-timeout "Direct link to 1-testeachtablename-fn-timeout") * `table`: `Array` of Arrays with the arguments that are passed into the test `fn` for each row. 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. * Or generate unique test titles by injecting properties of test case object with `$variable` * To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` (only works for ["own" properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) , e.g. `$variable.constructor.name` wouldn't work) * You can use `$#` to inject the index of the test case * You cannot use `$variable` with the `printf` formatting except for `%%` * `fn`: `Function` the test to be run, 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. The default timeout is 5 seconds. Example: test.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3],])('.add(%i, %i)', (a, b, expected) => { expect(a + b).toBe(expected);}); test.each([ {a: 1, b: 1, expected: 2}, {a: 1, b: 2, expected: 3}, {a: 2, b: 1, expected: 3},])('.add($a, $b)', ({a, b, expected}) => { expect(a + b).toBe(expected);}); #### 2\. ``test.each`table`(name, fn, timeout)``[​](https://jestjs.io/docs/29.7/api#2-testeachtablename-fn-timeout "Direct link to 2-testeachtablename-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` (only works for ["own" properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) , e.g. `$variable.constructor.name` wouldn't work) * `fn`: `Function` the test to be run, 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. The default timeout is 5 seconds. Example: test.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', ({a, b, expected}) => { expect(a + b).toBe(expected);}); ### `test.failing(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testfailingname-fn-timeout "Direct link to testfailingname-fn-timeout") Also under the alias: `it.failing(name, fn, timeout)` note This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. Use `test.failing` when you are writing a test and expecting it to fail. These tests will behave the other way normal tests do. If `failing` test will throw any errors then it will pass. If it does not throw it will fail. tip You can use this type of test i.e. when writing code in a BDD way. In that case the tests will not show up as failing until they pass. Then you can just remove the `failing` modifier to make them pass. It can also be a nice way to contribute failing tests to a project, even if you don't know how to fix the bug. Example: test.failing('it is not equal', () => { expect(5).toBe(6); // this test will pass});test.failing('it is equal', () => { expect(10).toBe(10); // this test will fail}); ### `test.failing.each(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testfailingeachname-fn-timeout "Direct link to testfailingeachname-fn-timeout") Also under the alias: `it.failing.each(table)(name, fn)` and ``it.failing.each`table`(name, fn)`` note This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. You can also run multiple tests at once by adding `each` after `failing`. Example: test.failing.each([ {a: 1, b: 1, expected: 2}, {a: 1, b: 2, expected: 3}, {a: 2, b: 1, expected: 3},])('.add($a, $b)', ({a, b, expected}) => { expect(a + b).toBe(expected);}); ### `test.only.failing(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testonlyfailingname-fn-timeout "Direct link to testonlyfailingname-fn-timeout") Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, fn, timeout)` note This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. Use `test.only.failing` if you want to only run a specific failing test. ### `test.skip.failing(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testskipfailingname-fn-timeout "Direct link to testskipfailingname-fn-timeout") Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, fn, timeout)`, `xtest.failing(name, fn, timeout)` note This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. Use `test.skip.failing` if you want to skip running a specific failing test. ### `test.only(name, fn, timeout)`[​](https://jestjs.io/docs/29.7/api#testonlyname-fn-timeout "Direct link to testonlyname-fn-timeout") Also under the aliases: `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. The default timeout is 5 seconds. For example, let's say you had these tests: 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)`[​](https://jestjs.io/docs/29.7/api#testonlyeachtablename-fn-1 "Direct link to testonlyeachtablename-fn-1") Also under the aliases: `it.only.each(table)(name, fn)`, `fit.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)`[​](https://jestjs.io/docs/29.7/api#testonlyeachtablename-fn-2 "Direct link to testonlyeachtablename-fn-2") 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 run', () => { expect(1 / 0).toBe(Infinity);}); #### ``test.only.each`table`(name, fn)``[​](https://jestjs.io/docs/29.7/api#testonlyeachtablename-fn-3 "Direct link to testonlyeachtablename-fn-3") test.only.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', ({a, b, expected}) => { expect(a + b).toBe(expected);});test('will not be run', () => { expect(1 / 0).toBe(Infinity);}); ### `test.skip(name, fn)`[​](https://jestjs.io/docs/29.7/api#testskipname-fn "Direct link to testskipname-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: 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)`[​](https://jestjs.io/docs/29.7/api#testskipeachtablename-fn "Direct link to testskipeachtablename-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)`[​](https://jestjs.io/docs/29.7/api#testskipeachtablename-fn-1 "Direct link to testskipeachtablename-fn-1") 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 run});test('will be run', () => { expect(1 / 0).toBe(Infinity);}); #### ``test.skip.each`table`(name, fn)``[​](https://jestjs.io/docs/29.7/api#testskipeachtablename-fn-2 "Direct link to testskipeachtablename-fn-2") test.skip.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3}`('returns $expected when $a is added to $b', ({a, b, expected}) => { expect(a + b).toBe(expected); // will not be run});test('will be run', () => { expect(1 / 0).toBe(Infinity);}); ### `test.todo(name)`[​](https://jestjs.io/docs/29.7/api#testtodoname "Direct link to testtodoname") 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. const add = (a, b) => a + b;test.todo('add should be associative'); tip `test.todo` will throw an error if you pass it a test callback function. Use [`test.skip`](https://jestjs.io/docs/29.7/api#testskipname-fn) instead, if you already implemented the test, but do not want it to run. TypeScript Usage[​](https://jestjs.io/docs/29.7/api#typescript-usage "Direct link to TypeScript Usage") -------------------------------------------------------------------------------------------------------- info The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs: import {expect, jest, test} from '@jest/globals'; Consult the [Getting Started](https://jestjs.io/docs/29.7/getting-started#using-typescript) guide for details on how to setup Jest with TypeScript. ### `.each`[​](https://jestjs.io/docs/29.7/api#each "Direct link to each") The `.each` modifier offers few different ways to define a table of the test cases. Some of the APIs have caveats related with the type inference of the arguments which are passed to `describe` or `test` callback functions. Let's take a look at each of them. note For simplicity `test.each` is picked for the examples, but the type inference is identical in all cases where `.each` modifier can be used: `describe.each`, `test.concurrent.only.each`, `test.skip.each`, etc. #### Array of objects[​](https://jestjs.io/docs/29.7/api#array-of-objects "Direct link to Array of objects") The array of objects API is most verbose, but it makes the type inference a painless task. A `table` can be inlined: import {test} from '@jest/globals';test.each([ {name: 'a', path: 'path/to/a', count: 1, write: true}, {name: 'b', path: 'path/to/b', count: 3},])('inline table', ({name, path, count, write}) => { // arguments are typed as expected, e.g. `write: boolean | undefined`}); Or declared separately as a variable: import {test} from '@jest/globals';const table = [ {a: 1, b: 2, expected: 'three', extra: true}, {a: 3, b: 4, expected: 'seven', extra: false}, {a: 5, b: 6, expected: 'eleven'},];test.each(table)('table as a variable', ({a, b, expected, extra}) => { // again everything is typed as expected, e.g. `extra: boolean | undefined`}); #### Array of arrays[​](https://jestjs.io/docs/29.7/api#array-of-arrays "Direct link to Array of arrays") The array of arrays style will work smoothly with inlined tables: import {test} from '@jest/globals';test.each([ [1, 2, 'three', true], [3, 4, 'seven', false], [5, 6, 'eleven'],])('inline table example', (a, b, expected, extra) => { // arguments are typed as expected, e.g. `extra: boolean | undefined`}); However, if a table is declared as a separate variable, it must be typed as an array of tuples for correct type inference (this is not needed only if all elements of a row are of the same type): import {test} from '@jest/globals';const table: Array<[number, number, string, boolean?]> = [ [1, 2, 'three', true], [3, 4, 'seven', false], [5, 6, 'eleven'],];test.each(table)('table as a variable example', (a, b, expected, extra) => { // without the annotation types are incorrect, e.g. `a: number | string | boolean`}); #### Template literal[​](https://jestjs.io/docs/29.7/api#template-literal "Direct link to Template literal") If all values are of the same type, the template literal API will type the arguments correctly: import {test} from '@jest/globals';test.each` a | b | expected ${1} | ${2} | ${3} ${3} | ${4} | ${7} ${5} | ${6} | ${11}`('template literal example', ({a, b, expected}) => { // all arguments are of type `number`}); Otherwise it will require a generic type argument: import {test} from '@jest/globals';test.each<{a: number; b: number; expected: string; extra?: boolean}>` a | b | expected | extra ${1} | ${2} | ${'three'} | ${true} ${3} | ${4} | ${'seven'} | ${false} ${5} | ${6} | ${'eleven'}`('template literal example', ({a, b, expected, extra}) => { // without the generic argument in this case types would default to `unknown`}); * [Methods](https://jestjs.io/docs/29.7/api#methods) * [Reference](https://jestjs.io/docs/29.7/api#reference) * [`afterAll(fn, timeout)`](https://jestjs.io/docs/29.7/api#afterallfn-timeout) * [`afterEach(fn, timeout)`](https://jestjs.io/docs/29.7/api#aftereachfn-timeout) * [`beforeAll(fn, timeout)`](https://jestjs.io/docs/29.7/api#beforeallfn-timeout) * [`beforeEach(fn, timeout)`](https://jestjs.io/docs/29.7/api#beforeeachfn-timeout) * [`describe(name, fn)`](https://jestjs.io/docs/29.7/api#describename-fn) * [`describe.each(table)(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#describeeachtablename-fn-timeout) * [`describe.only(name, fn)`](https://jestjs.io/docs/29.7/api#describeonlyname-fn) * [`describe.only.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#describeonlyeachtablename-fn) * [`describe.skip(name, fn)`](https://jestjs.io/docs/29.7/api#describeskipname-fn) * [`describe.skip.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#describeskipeachtablename-fn) * [`test(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testname-fn-timeout) * [`test.concurrent(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testconcurrentname-fn-timeout) * [`test.concurrent.each(table)(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testconcurrenteachtablename-fn-timeout) * [`test.concurrent.only.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testconcurrentonlyeachtablename-fn) * [`test.concurrent.skip.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testconcurrentskipeachtablename-fn) * [`test.each(table)(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testeachtablename-fn-timeout) * [`test.failing(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testfailingname-fn-timeout) * [`test.failing.each(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testfailingeachname-fn-timeout) * [`test.only.failing(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testonlyfailingname-fn-timeout) * [`test.skip.failing(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testskipfailingname-fn-timeout) * [`test.only(name, fn, timeout)`](https://jestjs.io/docs/29.7/api#testonlyname-fn-timeout) * [`test.only.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testonlyeachtablename-fn-1) * [`test.skip(name, fn)`](https://jestjs.io/docs/29.7/api#testskipname-fn) * [`test.skip.each(table)(name, fn)`](https://jestjs.io/docs/29.7/api#testskipeachtablename-fn) * [`test.todo(name)`](https://jestjs.io/docs/29.7/api#testtodoname) * [TypeScript Usage](https://jestjs.io/docs/29.7/api#typescript-usage) * [`.each`](https://jestjs.io/docs/29.7/api#each) --- # Getting Started · Jest [Skip to main content](https://jestjs.io/docs/29.7/getting-started#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/getting-started) ** (30.0). Version: 29.7 On this page Install Jest using your favorite package manager: * npm * Yarn * pnpm npm install --save-dev jest yarn add --dev jest pnpm add --save-dev jest Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a `sum.js` file: function sum(a, b) { return a + b;}module.exports = sum; Then, create a file named `sum.test.js`. This will contain our actual test: const sum = require('./sum');test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3);}); Add the following section to your `package.json`: { "scripts": { "test": "jest" }} Finally, run `yarn test` or `npm test` and Jest will print this message: PASS ./sum.test.js✓ adds 1 + 2 to equal 3 (5ms) **You just successfully wrote your first test using Jest!** This test used `expect` and `toBe` to test that two values were exactly identical. To learn about the other things that Jest can test, see [Using Matchers](https://jestjs.io/docs/29.7/using-matchers) . Running from command line[​](https://jestjs.io/docs/29.7/getting-started#running-from-command-line "Direct link to Running from command line") ----------------------------------------------------------------------------------------------------------------------------------------------- You can run Jest directly from the CLI (if it's globally available in your `PATH`, e.g. by `yarn global add jest` or `npm install jest --global`) with a variety of useful options. Here's how to run Jest on files matching `my-test`, using `config.json` as a configuration file and display a native OS notification after the run: jest my-test --notify --config=config.json If you'd like to learn more about running `jest` through the command line, take a look at the [Jest CLI Options](https://jestjs.io/docs/29.7/cli) page. Additional Configuration[​](https://jestjs.io/docs/29.7/getting-started#additional-configuration "Direct link to Additional Configuration") -------------------------------------------------------------------------------------------------------------------------------------------- ### Generate a basic configuration file[​](https://jestjs.io/docs/29.7/getting-started#generate-a-basic-configuration-file "Direct link to Generate a basic configuration file") Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option: * npm * Yarn * pnpm npm init jest@latest yarn create jest pnpm create jest ### Using Babel[​](https://jestjs.io/docs/29.7/getting-started#using-babel "Direct link to Using Babel") To use [Babel](https://babeljs.io/) , install required dependencies: * npm * Yarn * pnpm npm install --save-dev babel-jest @babel/core @babel/preset-env yarn add --dev babel-jest @babel/core @babel/preset-env pnpm add --save-dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: babel.config.js module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]],}; The ideal configuration for Babel will depend on your project. See [Babel's docs](https://babeljs.io/docs/en/) for more details. **Making your Babel config jest-aware** Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. babel.config.js module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. return { // ... };}; note `babel-jest` is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the `transform` configuration option: jest.config.js module.exports = { transform: {},}; ### Using webpack[​](https://jestjs.io/docs/29.7/getting-started#using-webpack "Direct link to Using webpack") Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the [webpack guide](https://jestjs.io/docs/29.7/webpack) to get started. ### Using Vite[​](https://jestjs.io/docs/29.7/getting-started#using-vite "Direct link to Using Vite") Jest can be used in projects that use [vite](https://vitejs.dev/) to serve source code over native ESM to provide some frontend tooling, vite is an opinionated tool and does offer some out-of-the box workflows. Jest is not fully supported by vite due to how the [plugin system](https://github.com/vitejs/vite/issues/1955#issuecomment-776009094) from vite works, but there are some working examples for first-class jest integration using `vite-jest`, since this is not fully supported, you might as well read the [limitation of the `vite-jest`](https://github.com/sodatea/vite-jest/tree/main/packages/vite-jest#limitations-and-differences-with-commonjs-tests) . Refer to the [vite guide](https://vitejs.dev/guide/) to get started. ### Using Parcel[​](https://jestjs.io/docs/29.7/getting-started#using-parcel "Direct link to Using Parcel") Jest can be used in projects that use [parcel-bundler](https://parceljs.org/) to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official [docs](https://parceljs.org/docs/) to get started. ### Using TypeScript[​](https://jestjs.io/docs/29.7/getting-started#using-typescript "Direct link to Using TypeScript") #### Via `babel`[​](https://jestjs.io/docs/29.7/getting-started#via-babel "Direct link to via-babel") Jest supports TypeScript, via Babel. First, make sure you followed the instructions on [using Babel](https://jestjs.io/docs/29.7/getting-started#using-babel) above. Next, install the `@babel/preset-typescript`: * npm * Yarn * pnpm npm install --save-dev @babel/preset-typescript yarn add --dev @babel/preset-typescript pnpm add --save-dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. babel.config.js module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], '@babel/preset-typescript', ],}; However, there are some [caveats](https://babeljs.io/docs/en/babel-plugin-transform-typescript#caveats) to using TypeScript with Babel. Because TypeScript support in Babel is purely transpilation, Jest will not type-check your tests as they are run. If you want that, you can use [ts-jest](https://github.com/kulshekhar/ts-jest) instead, or just run the TypeScript compiler [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) separately (or as part of your build process). #### Via `ts-jest`[​](https://jestjs.io/docs/29.7/getting-started#via-ts-jest "Direct link to via-ts-jest") [ts-jest](https://github.com/kulshekhar/ts-jest) is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript. * npm * Yarn * pnpm npm install --save-dev ts-jest yarn add --dev ts-jest pnpm add --save-dev ts-jest In order for Jest to transpile TypeScript with `ts-jest`, you may also need to create a [configuration](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation#jest-config-file) file. #### Type definitions[​](https://jestjs.io/docs/29.7/getting-started#type-definitions "Direct link to Type definitions") There are two ways to have [Jest global APIs](https://jestjs.io/docs/29.7/api) typed for test files written in TypeScript. You can use type definitions which ships with Jest and will update each time you update Jest. Install the `@jest/globals` package: * npm * Yarn * pnpm npm install --save-dev @jest/globals yarn add --dev @jest/globals pnpm add --save-dev @jest/globals And import the APIs from it: sum.test.ts import {describe, expect, test} from '@jest/globals';import {sum} from './sum';describe('sum module', () => { test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });}); tip See the additional usage documentation of [`describe.each`/`test.each`](https://jestjs.io/docs/29.7/api#typescript-usage) and [`mock functions`](https://jestjs.io/docs/29.7/mock-function-api#typescript-usage) . Or you may choose to install the [`@types/jest`](https://npmjs.com/package/@types/jest) package. It provides types for Jest globals without a need to import them. * npm * Yarn * pnpm npm install --save-dev @types/jest yarn add --dev @types/jest pnpm add --save-dev @types/jest info `@types/jest` is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) , hence the latest Jest features or versions may not be covered yet. Try to match versions of Jest and `@types/jest` as closely as possible. For example, if you are using Jest `27.4.0` then installing `27.4.x` of `@types/jest` is ideal. ### Using ESLint[​](https://jestjs.io/docs/29.7/getting-started#using-eslint "Direct link to Using ESLint") Jest can be used with ESLint without any further configuration as long as you import the [Jest global helpers](https://jestjs.io/docs/29.7/api) (`describe`, `it`, etc.) from `@jest/globals` before using them in your test file. This is necessary to avoid `no-undef` errors from ESLint, which doesn't know about the Jest globals. If you'd like to avoid these imports, you can configure your [ESLint environment](https://eslint.org/docs/latest/use/configure/language-options#specifying-environments) to support these globals by adding the `jest` environment: { "overrides": [ { "files": ["tests/**/*"], "env": { "jest": true } } ]} Or use [`eslint-plugin-jest`](https://github.com/jest-community/eslint-plugin-jest) , which has a similar effect: { "overrides": [ { "files": ["tests/**/*"], "plugins": ["jest"], "env": { "jest/globals": true } } ]} * [Running from command line](https://jestjs.io/docs/29.7/getting-started#running-from-command-line) * [Additional Configuration](https://jestjs.io/docs/29.7/getting-started#additional-configuration) * [Generate a basic configuration file](https://jestjs.io/docs/29.7/getting-started#generate-a-basic-configuration-file) * [Using Babel](https://jestjs.io/docs/29.7/getting-started#using-babel) * [Using webpack](https://jestjs.io/docs/29.7/getting-started#using-webpack) * [Using Vite](https://jestjs.io/docs/29.7/getting-started#using-vite) * [Using Parcel](https://jestjs.io/docs/29.7/getting-started#using-parcel) * [Using TypeScript](https://jestjs.io/docs/29.7/getting-started#using-typescript) * [Using ESLint](https://jestjs.io/docs/29.7/getting-started#using-eslint) --- # ECMAScript Modules · Jest [Skip to main content](https://jestjs.io/docs/29.7/ecmascript-modules#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/ecmascript-modules) ** (30.0). Version: 29.7 On this page caution Jest ships with **experimental** support for ECMAScript Modules (ESM). The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). With the warnings out of the way, this is how you activate ESM support in your tests. 1. Ensure you either disable [code transforms](https://jestjs.io/docs/29.7/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object) by passing `transform: {}` or otherwise configure your transformer to emit ESM rather than the default CommonJS (CJS). 2. Execute `node` with `--experimental-vm-modules`, e.g. `node --experimental-vm-modules node_modules/jest/bin/jest.js` or `NODE_OPTIONS="$NODE_OPTIONS --experimental-vm-modules" npx jest` etc. On Windows, you can use [`cross-env`](https://github.com/kentcdodds/cross-env) to be able to set environment variables. If you use Yarn, you can use `yarn node --experimental-vm-modules $(yarn bin jest)`. This command will also work if you use [Yarn Plug'n'Play](https://yarnpkg.com/features/pnp) . If your codebase includes ESM imports from `*.wasm` files, you do _not_ need to pass `--experimental-wasm-modules` to `node`. Current implementation of WebAssembly imports in Jest relies on experimental VM modules, however, this may change in the future. 3. Beyond that, we attempt to follow `node`'s logic for activating "ESM mode" (such as looking at `type` in `package.json` or `.mjs` files), see [their docs](https://nodejs.org/api/esm.html#esm_enabling) for details. 4. If you want to treat other file extensions (such as `.jsx` or `.ts`) as ESM, please use the [`extensionsToTreatAsEsm` option](https://jestjs.io/docs/29.7/configuration#extensionstotreatasesm-arraystring) . Differences between ESM and CommonJS[​](https://jestjs.io/docs/29.7/ecmascript-modules#differences-between-esm-and-commonjs "Direct link to Differences between ESM and CommonJS") ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Most of the differences are explained in [Node's documentation](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs) , but in addition to the things mentioned there, Jest injects a special variable into all executed files - the [`jest` object](https://jestjs.io/docs/29.7/jest-object) . To access this object in ESM, you need to import it from the `@jest/globals` module or use `import.meta`. import {jest} from '@jest/globals';jest.useFakeTimers();// etc.// alternativelyimport.meta.jest.useFakeTimers();// jest === import.meta.jest => true Module mocking in ESM[​](https://jestjs.io/docs/29.7/ecmascript-modules#module-mocking-in-esm "Direct link to Module mocking in ESM") -------------------------------------------------------------------------------------------------------------------------------------- Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: import {jest} from '@jest/globals';jest.unstable_mockModule('node:child_process', () => ({ execSync: jest.fn(), // etc.}));const {execSync} = await import('node:child_process');// etc. For mocking CJS modules, you should continue to use `jest.mock`. See the example below: main.cjs const {BrowserWindow, app} = require('electron');// etc.module.exports = {example}; main.test.cjs import {createRequire} from 'node:module';import {jest} from '@jest/globals';const require = createRequire(import.meta.url);jest.mock('electron', () => ({ app: { on: jest.fn(), whenReady: jest.fn(() => Promise.resolve()), }, BrowserWindow: jest.fn().mockImplementation(() => ({ // partial mocks. })),}));const {BrowserWindow} = require('electron');const exported = require('./main.cjs');// alternativelyconst {BrowserWindow} = (await import('electron')).default;const exported = await import('./main.cjs');// etc. * [Differences between ESM and CommonJS](https://jestjs.io/docs/29.7/ecmascript-modules#differences-between-esm-and-commonjs) * [Module mocking in ESM](https://jestjs.io/docs/29.7/ecmascript-modules#module-mocking-in-esm) --- # Jest Platform · Jest [Skip to main content](https://jestjs.io/docs/29.7/jest-platform#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/jest-platform) ** (30.0). Version: 29.7 On this page 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[​](https://jestjs.io/docs/29.7/jest-platform#jest-changed-files "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example "Direct link to Example") const {getChangedFilesForRoots} = require('jest-changed-files');// print the set of modified files since last commit in the current repogetChangedFilesForRoots(['./'], { lastCommit: true,}).then(result => console.log(result.changedFiles)); You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md) . jest-diff[​](https://jestjs.io/docs/29.7/jest-platform#jest-diff "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example-1 "Direct link to Example") const {diff} = require('jest-diff');const a = {a: {b: {c: 5}}};const b = {a: {b: {c: 6}}};const result = diff(a, b);// print diffconsole.log(result); jest-docblock[​](https://jestjs.io/docs/29.7/jest-platform#jest-docblock "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example-2 "Direct link to Example") 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/jestjs/jest/blob/main/packages/jest-docblock/README.md) . jest-get-type[​](https://jestjs.io/docs/29.7/jest-platform#jest-get-type "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example-3 "Direct link to Example") 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[​](https://jestjs.io/docs/29.7/jest-platform#jest-validate "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example-4 "Direct link to Example") 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/jestjs/jest/blob/main/packages/jest-validate/README.md) . jest-worker[​](https://jestjs.io/docs/29.7/jest-platform#jest-worker "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example-5 "Direct link to Example") heavy-task.js module.exports = { myHeavyTask: args => { // long running CPU intensive task. },}; 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/jestjs/jest/blob/main/packages/jest-worker/README.md) . pretty-format[​](https://jestjs.io/docs/29.7/jest-platform#pretty-format "Direct link to 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[​](https://jestjs.io/docs/29.7/jest-platform#example-6 "Direct link to Example") const {format: 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/jestjs/jest/blob/main/packages/pretty-format/README.md) . * [jest-changed-files](https://jestjs.io/docs/29.7/jest-platform#jest-changed-files) * [Example](https://jestjs.io/docs/29.7/jest-platform#example) * [jest-diff](https://jestjs.io/docs/29.7/jest-platform#jest-diff) * [Example](https://jestjs.io/docs/29.7/jest-platform#example-1) * [jest-docblock](https://jestjs.io/docs/29.7/jest-platform#jest-docblock) * [Example](https://jestjs.io/docs/29.7/jest-platform#example-2) * [jest-get-type](https://jestjs.io/docs/29.7/jest-platform#jest-get-type) * [Example](https://jestjs.io/docs/29.7/jest-platform#example-3) * [jest-validate](https://jestjs.io/docs/29.7/jest-platform#jest-validate) * [Example](https://jestjs.io/docs/29.7/jest-platform#example-4) * [jest-worker](https://jestjs.io/docs/29.7/jest-platform#jest-worker) * [Example](https://jestjs.io/docs/29.7/jest-platform#example-5) * [pretty-format](https://jestjs.io/docs/29.7/jest-platform#pretty-format) * [Example](https://jestjs.io/docs/29.7/jest-platform#example-6) --- # Environment Variables · Jest [Skip to main content](https://jestjs.io/docs/next/environment-variables#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is unreleased documentation for Jest **Next** version. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/environment-variables) ** (30.0). Version: Next On this page Jest sets the following environment variables: ### `NODE_ENV`[​](https://jestjs.io/docs/next/environment-variables#node_env "Direct link to node_env") Set to `'test'` if it's not already set to something else. ### `JEST_WORKER_ID`[​](https://jestjs.io/docs/next/environment-variables#jest_worker_id "Direct link to jest_worker_id") Each worker process is assigned a unique id (index-based that starts with `1`). This is set to `1` for all tests when [`runInBand`](https://jestjs.io/docs/next/cli#--runinband) is set to true. * [`NODE_ENV`](https://jestjs.io/docs/next/environment-variables#node_env) * [`JEST_WORKER_ID`](https://jestjs.io/docs/next/environment-variables#jest_worker_id) --- # Testing React Native Apps · Jest [Skip to main content](https://jestjs.io/docs/29.7/tutorial-react-native#__docusaurus_skipToContent_fallback) Support Ukraine 🇺🇦 [Help Provide Humanitarian Aid to Ukraine](https://opensource.facebook.com/support-ukraine) . This is documentation for Jest **29.7**, which is no longer actively maintained. For up-to-date documentation, see the **[latest version](https://jestjs.io/docs/tutorial-react-native) ** (30.0). Version: 29.7 On this page At Facebook, we use Jest to test [React Native](https://reactnative.dev/) applications. Get a deeper insight into testing a working React Native app example by reading the following series: [Part 1: Jest – Snapshot come into play](https://callstack.com/blog/testing-react-native-with-the-new-jest-part-1-snapshots-come-into-play/) and [Part 2: Jest – Redux Snapshots for your Actions and Reducers](https://callstack.com/blog/testing-react-native-with-the-new-jest-part-2-redux-snapshots-for-your-actions-and-reducers/) . Setup[​](https://jestjs.io/docs/29.7/tutorial-react-native#setup "Direct link to Setup") ----------------------------------------------------------------------------------------- Starting from react-native version 0.38, a Jest setup is included by default when running `react-native init`. The following configuration should be automatically added to your package.json file: { "scripts": { "test": "jest" }, "jest": { "preset": "react-native" }} Run `yarn test` to run tests with Jest. tip If you are upgrading your react-native application and previously used the `jest-react-native` preset, remove the dependency from your `package.json` file and change the preset to `react-native` instead. Snapshot Test[​](https://jestjs.io/docs/29.7/tutorial-react-native#snapshot-test "Direct link to Snapshot Test") ----------------------------------------------------------------------------------------------------------------- Let's create a [snapshot test](https://jestjs.io/docs/29.7/snapshot-testing) for a small intro component with a few views and text components and some styles: Intro.js import React, {Component} from 'react';import {StyleSheet, Text, View} from 'react-native';class Intro extends Component { render() { return ( Welcome to React Native! This is a React Native snapshot test. ); }}const styles = StyleSheet.create({ container: { alignItems: 'center', backgroundColor: '#F5FCFF', flex: 1, justifyContent: 'center', }, instructions: { color: '#333333', marginBottom: 5, textAlign: 'center', }, welcome: { fontSize: 20, margin: 10, textAlign: 'center', },});export default Intro; Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file: \_\_tests\_\_/Intro-test.js import React from 'react';import renderer from 'react-test-renderer';import Intro from '../Intro';test('renders correctly', () => { const tree = renderer.create().toJSON(); expect(tree).toMatchSnapshot();}); When you run `yarn test` or `jest`, this will produce an output file like this: \_\_tests\_\_/\_\_snapshots\_\_/Intro-test.js.snap exports[`Intro renders correctly 1`] = ` Welcome to React Native! This is a React Native snapshot test. `; The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native) . Preset configuration[​](https://jestjs.io/docs/29.7/tutorial-react-native#preset-configuration "Direct link to Preset configuration") -------------------------------------------------------------------------------------------------------------------------------------- The preset sets up the environment and is very opinionated and based on what we found to be useful at Facebook. All of the configuration options can be overwritten just as they can be customized when no preset is used. ### Environment[​](https://jestjs.io/docs/29.7/tutorial-react-native#environment "Direct link to Environment") `react-native` ships with a Jest preset, so the `jest.preset` field of your `package.json` should point to `react-native`. The preset is a node environment that mimics the environment of a React Native app. Because it doesn't load any DOM or browser APIs, it greatly improves Jest's startup time. ### transformIgnorePatterns customization[​](https://jestjs.io/docs/29.7/tutorial-react-native#transformignorepatterns-customization "Direct link to transformIgnorePatterns customization") The [`transformIgnorePatterns`](https://jestjs.io/docs/29.7/configuration#transformignorepatterns-arraystring) option can be used to specify which files shall be transformed by Babel. Many `react-native` npm modules unfortunately don't pre-compile their source code before publishing. By default the `jest-react-native` preset only processes the project's own source files and `react-native`. If you have npm dependencies that have to be transformed you can customize this configuration option by including modules other than `react-native` by grouping them and separating them with the `|` operator: { "transformIgnorePatterns": ["node_modules/(?!((@)?react-native|my-project)/)"]} You can test which paths would match (and thus be excluded from transformation) with a tool [like this](https://regex101.com/r/JsLIDM/1) . `transformIgnorePatterns` will exclude a file from transformation if the path matches against **any** pattern provided. Splitting into multiple patterns could therefore have unintended results if you are not careful. In the example below, the exclusion (also known as a negative lookahead assertion) for `foo` and `bar` cancel each other out: { "transformIgnorePatterns": ["node_modules/(?!foo/)", "node_modules/(?!bar/)"] // not what you want} ### setupFiles[​](https://jestjs.io/docs/29.7/tutorial-react-native#setupfiles "Direct link to setupFiles") If you'd like to provide additional configuration for every test file, the [`setupFiles` configuration option](https://jestjs.io/docs/29.7/configuration#setupfiles-array) can be used to specify setup scripts. ### moduleNameMapper[​](https://jestjs.io/docs/29.7/tutorial-react-native#modulenamemapper "Direct link to moduleNameMapper") The [`moduleNameMapper`](https://jestjs.io/docs/29.7/configuration#modulenamemapper-objectstring-string--arraystring) can be used to map a module path to a different module. By default the preset maps all images to an image stub module but if a module cannot be found this configuration option can help: { "moduleNameMapper": { "my-module.js": "/path/to/my-module.js" }} Tips[​](https://jestjs.io/docs/29.7/tutorial-react-native#tips "Direct link to Tips") -------------------------------------------------------------------------------------- ### Mock native modules using jest.mock[​](https://jestjs.io/docs/29.7/tutorial-react-native#mock-native-modules-using-jestmock "Direct link to Mock native modules using jest.mock") The Jest preset built into `react-native` comes with a few default mocks that are applied on a react-native repository. However, some react-native components or third party components rely on native code to be rendered. In such cases, Jest's manual mocking system can help to mock out the underlying implementation. For example, if your code depends on a third party native video component called `react-native-video` you might want to stub it out with a manual mock like this: jest.mock('react-native-video', () => 'Video'); This will render the component as `