### Setup and Run Jest Website Development Server Source: https://github.com/jestjs/jest/blob/main/CONTRIBUTING.md Install website-specific dependencies and start a development server to test documentation and website changes. Includes fetching supporters data and running the local development server from the website directory. ```bash $ cd website $ yarn $ node fetchSupporters.js $ yarn start ``` -------------------------------- ### Illustrate Jest `before*` and `after*` hook execution order Source: https://github.com/jestjs/jest/blob/main/docs/SetupAndTeardown.md This example demonstrates the precise order in which Jest executes `beforeAll`, `afterAll`, `beforeEach`, and `afterEach` hooks, especially when nested within `describe` blocks. Understanding this order is crucial for predicting test behavior and ensuring correct setup and teardown logic. The output comments show the sequence of console logs. ```js beforeAll(() => console.log('1 - beforeAll')); afterAll(() => console.log('1 - afterAll')); beforeEach(() => console.log('1 - beforeEach')); afterEach(() => console.log('1 - afterEach')); test('', () => console.log('1 - test')); describe('Scoped / Nested block', () => { beforeAll(() => console.log('2 - beforeAll')); afterAll(() => console.log('2 - afterAll')); beforeEach(() => console.log('2 - beforeEach')); afterEach(() => console.log('2 - afterEach')); test('', () => console.log('2 - test')); }); // 1 - beforeAll // 1 - beforeEach // 1 - test // 1 - afterEach // 2 - beforeAll // 1 - beforeEach // 2 - beforeEach // 2 - test // 2 - afterEach // 1 - afterEach // 2 - afterAll // 1 - afterAll ``` -------------------------------- ### Install Babel and `babel-jest` for Jest integration Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md Installs the necessary Babel packages, including `babel-jest`, `@babel/core`, and `@babel/preset-env`, as development dependencies. These are required to transpile modern JavaScript syntax for Jest tests. ```bash npm install --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Install ts-jest for TypeScript Support in Jest Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This command installs `ts-jest` as a development dependency, providing a TypeScript preprocessor for Jest. `ts-jest` handles transpilation and source map support, offering an alternative to Babel for running TypeScript tests with Jest. ```bash npm install --save-dev ts-jest ``` -------------------------------- ### Configure repeating synchronous setup and teardown for Jest tests Source: https://github.com/jestjs/jest/blob/main/docs/SetupAndTeardown.md Use `beforeEach` and `afterEach` hooks in Jest to execute setup and teardown logic repeatedly before and after each test. This is useful for tasks like initializing and clearing a database that needs to be reset for every test case. The example demonstrates calling synchronous functions `initializeCityDatabase()` and `clearCityDatabase()`. ```js beforeEach(() => { initializeCityDatabase(); }); afterEach(() => { clearCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); ``` -------------------------------- ### Generate a basic Jest configuration file interactively Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md Uses `npm init jest@latest` to interactively generate a `jest.config.js` file. This command helps set up a basic configuration based on project-specific questions. ```bash npm init jest@latest ``` -------------------------------- ### Install Babel TypeScript Preset for Jest Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This command installs the `@babel/preset-typescript` package as a development dependency, enabling Babel to transpile TypeScript files within a Jest project. It's a prerequisite for using TypeScript with Jest via Babel. ```bash npm install --save-dev @babel/preset-typescript ``` -------------------------------- ### Configure test setup hooks and matchers in JavaScript Source: https://github.com/jestjs/jest/blob/main/docs/Configuration.md Runs immediately after the test framework is installed, allowing access to Jest globals like expect and afterEach hooks. ```javascript const matchers = require('jest-extended'); expect.extend(matchers); afterEach(() => { jest.useRealTimers(); }); ``` -------------------------------- ### beforeAll - Run setup before all tests start Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md Executes a function before any tests in a file run. Supports promises and generators, allowing asynchronous setup with optional timeout parameter (default 5 seconds). Jest waits for promise resolution before running tests. When inside a describe block, runs at the beginning of that block. ```javascript 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); }); }); ``` -------------------------------- ### Start development server from repository root Source: https://github.com/jestjs/jest/blob/main/website/README.md Starts the website development server from the Jest monorepo root using Yarn workspaces. ```bash yarn workspace jest-website start ``` -------------------------------- ### SourceMapSupport#install(sourceMaps?: SourceMapRegistry | null, options?: SourceMapSupportInstallOptions): void Source: https://github.com/jestjs/jest/blob/main/packages/jest-source-map/README.md Replaces Error.prepareStackTrace in the current realm so that reading .stack on any error renders frames against the original source files. Stays installed for the lifetime of the process. ```APIDOC ## SourceMapSupport#install ### Description Replaces `Error.prepareStackTrace` in the current realm, so reading `.stack` on any error renders frames against the original sources. Each call swaps in a new registry. ### Signature ```typescript install(sourceMaps?: SourceMapRegistry | null, options?: SourceMapSupportInstallOptions): void ``` ### Parameters - **sourceMaps** (`SourceMapRegistry | null`, optional) - A `Map` mapping transformed file paths to source map (`.map`) file paths. Files missing from the registry fall back to `sourceMappingURL` comments. - **options** (`SourceMapSupportInstallOptions`, optional) - Optional configuration object. - **suppressWarnings** (`boolean`, optional) - Set to `true` to disable reporting unparseable source maps via `console.warn`. ### Returns - `void` ### Example ```javascript import {SourceMapSupport} from '@jest/source-map'; const sourceMapSupport = new SourceMapSupport(); sourceMapSupport.install(new Map([['/build/app.js', '/cache/app.js.map']])); new Error('boom').stack; // Error: boom // at greet (/src/app.ts:12:9) ``` ``` -------------------------------- ### Install Jest Type Definitions from DefinitelyTyped Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This command installs the `@types/jest` package as a development dependency, providing global type definitions for Jest APIs. This allows TypeScript to understand Jest's global functions without explicit imports, though it's maintained by the DefinitelyTyped community and may not always be perfectly in sync with the latest Jest versions. ```bash npm install --save-dev @types/jest ``` -------------------------------- ### Install Jest Globals for TypeScript Type Definitions Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This command installs the `@jest/globals` package as a development dependency. This package provides type definitions for Jest's global APIs, allowing TypeScript to correctly type-check Jest functions like `describe`, `expect`, and `test` when imported explicitly. ```bash npm install --save-dev @jest/globals ``` -------------------------------- ### beforeEach Setup with Database Reset Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md Demonstrates using beforeEach to reset global state before each test. The function returns a promise that Jest waits for before running tests. This example clears a database and inserts test data, ensuring a clean state for each test case. ```javascript 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(); }); }); ``` -------------------------------- ### Create a conditional Babel configuration for Jest environment Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md Illustrates how to make a `babel.config.js` configuration dynamic based on the environment. It uses `api.env('test')` to apply specific presets or plugins only when Jest is running. ```javascript module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. return { // ... }; }; ``` -------------------------------- ### Run Jest Performance Benchmark with Hyperfine Source: https://github.com/jestjs/jest/blob/main/benchmarks/test-file-overhead/README.md Execute hyperfine benchmarking tool to compare Jest performance against another Jest clone. The command runs 10 measurements with 3 warmup runs, comparing the main Jest installation against an alternative version for performance analysis. ```bash hyperfine -w 3 -m 10 ../../jest /tmp/other-jest-clone-to-compare-against/jest ``` -------------------------------- ### Perform one-time asynchronous setup and teardown for Jest tests Source: https://github.com/jestjs/jest/blob/main/docs/SetupAndTeardown.md Utilize `beforeAll` and `afterAll` hooks for setup and teardown tasks that only need to run once per test file, rather than before/after each individual test. These hooks can also handle asynchronous operations by returning a Promise, ensuring that resources are prepared once at the beginning and cleaned up once at the end. This is efficient for shared resources like a database that can be reused across multiple tests. ```js beforeAll(() => { return initializeCityDatabase(); }); afterAll(() => { return clearCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); ``` -------------------------------- ### Handle asynchronous repeating setup in Jest with `beforeEach` Source: https://github.com/jestjs/jest/blob/main/docs/SetupAndTeardown.md When your setup function returns a Promise, `beforeEach` can handle asynchronous operations by returning that Promise. Jest will wait for the Promise to resolve before running the test, ensuring that the necessary setup is complete. This pattern is crucial for operations like database initialization that might take time. ```js beforeEach(() => { return initializeCityDatabase(); }); ``` -------------------------------- ### Run a single test suite using `describe.only` in Jest Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md This example demonstrates `describe.only` (or `fdescribe`), which executes only a specific `describe` block while skipping all others. This is useful for focusing on a particular set of tests during development or debugging. ```js describe.only('my beverage', () => { test('is delicious', () => { expect(myBeverage.delicious).toBeTruthy(); }); test('is not sour', () => { expect(myBeverage.sour).toBeFalsy(); }); }); describe('my other beverage', () => { // ... will be skipped }); ``` -------------------------------- ### Install dependencies in monorepo root Source: https://github.com/jestjs/jest/blob/main/website/README.md Run this command from the repository root directory to install required project dependencies. ```bash yarn ``` -------------------------------- ### Install @jest/source-map using npm Source: https://github.com/jestjs/jest/blob/main/packages/jest-source-map/README.md Installs the package into your project dependencies. ```sh $ npm install --save @jest/source-map ``` -------------------------------- ### Install jest-haste-map via npm or yarn Source: https://github.com/jestjs/jest/blob/main/packages/jest-haste-map/README.md Install jest-haste-map as a development dependency. ```bash npm install jest-haste-map --save-dev ``` ```bash yarn add jest-haste-map --dev ``` -------------------------------- ### Verify Node.js Installation (Shell) Source: https://github.com/jestjs/jest/blob/main/CONTRIBUTING.md Command to check the installed version of Node.js. It's crucial to ensure a compatible version (e.g., v20.x) is installed as recommended by the project. ```sh node -v ``` -------------------------------- ### Install jest-docblock package Source: https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md Installation instructions for jest-docblock using either yarn or npm package managers. Choose the appropriate command based on your project's package manager preference. ```shell # with yarn yarn add jest-docblock ``` ```shell # with npm npm install jest-docblock ``` -------------------------------- ### Install jest-dynamodb npm package Source: https://github.com/jestjs/jest/blob/main/docs/DynamoDB.md Install the @shelf/jest-dynamodb package as a development dependency to enable DynamoDB integration with Jest. ```bash npm install --save-dev @shelf/jest-dynamodb ``` -------------------------------- ### Install Project Dependencies (Yarn) Source: https://github.com/jestjs/jest/blob/main/CONTRIBUTING.md Command to install all necessary project dependencies using Yarn. Ensure `corepack enable` has been run beforehand to manage package managers like Yarn. ```sh yarn install ``` -------------------------------- ### Install React Native testing dependencies using Yarn Source: https://github.com/jestjs/jest/blob/main/docs/TutorialReactNative.md Install @testing-library/react-native and its peer dependency test-renderer as dev dependencies. ```bash yarn add --dev @testing-library/react-native test-renderer ``` -------------------------------- ### Define worker lifecycle methods setup and teardown Source: https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md Defines optional asynchronous setup() and teardown() methods in the worker file. setup() executes before the first call to any method, and teardown() executes when the farm ends. Both methods are optional and can perform initialization and cleanup operations. ```javascript export async function setup() { // Executed before the first call to any method in the child } export async function teardown() { // Executed when the farm ends } ``` -------------------------------- ### Install babel-preset-jest using npm Source: https://github.com/jestjs/jest/blob/main/packages/babel-preset-jest/README.md This command installs the `babel-preset-jest` package as a development dependency in your project. It is required to use the Jest Babel preset for transforming code. ```sh $ npm install --save-dev babel-preset-jest ``` -------------------------------- ### Import Jest APIs in TypeScript Source: https://github.com/jestjs/jest/blob/main/docs/_TypeScriptExamplesNote.md Import the core Jest APIs (expect, jest, test) from @jest/globals package in TypeScript files. This import statement is required for TypeScript examples to work as documented. Refer to the Getting Started guide for complete Jest TypeScript setup instructions. ```typescript import {expect, jest, test} from '@jest/globals'; ``` -------------------------------- ### Start development server from website directory Source: https://github.com/jestjs/jest/blob/main/website/README.md Launches the local Docusaurus development server from inside the website folder. ```bash yarn start ``` -------------------------------- ### onRunStart(results, options) Source: https://github.com/jestjs/jest/blob/main/packages/jest-reporters/CLAUDE.md Called at the beginning of a test run, allowing reporters to perform setup or initial logging. ```APIDOC ## Method: `onRunStart`\n\n### Description\nCalled at the beginning of a test run, allowing reporters to perform setup or initial logging.\n\n### Signature\n```typescript\nonRunStart?(results, options): Promise | void;\n```\n\n### Parameters\n- **results** (any) - The initial test results object.\n- **options** (any) - Configuration options for the test run.\n\n### Returns\n(Promise | void) - A promise that resolves when the operation is complete, or void if synchronous. ``` -------------------------------- ### Initialize Jest Project Source: https://github.com/jestjs/jest/blob/main/packages/create-jest/README.md Use these commands to quickly set up a new Jest project with your preferred package manager. ```bash npm init jest@latest ``` ```bash yarn create jest ``` ```bash pnpm create jest ``` -------------------------------- ### Navigate to the website directory Source: https://github.com/jestjs/jest/blob/main/website/README.md Switch into the website directory before executing local site scripts. ```bash cd website ``` -------------------------------- ### Install jest-create-cache-key-function via npm Source: https://github.com/jestjs/jest/blob/main/packages/jest-create-cache-key-function/README.md Install the @jest/create-cache-key-function package as a development dependency. This is required before using the createCacheKey function in your Jest transformer setup. ```bash npm install --save-dev @jest/create-cache-key-function ``` -------------------------------- ### Configure ESLint to Recognize Jest Global Variables Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This ESLint configuration snippet defines a setup that recognizes Jest's global variables (like `describe`, `it`, `expect`) within JavaScript files. By extending `globals.jest`, it prevents `no-undef` errors without requiring explicit imports of Jest APIs in every test file. ```javascript 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', }, }, ]); ``` -------------------------------- ### Install pretty-format via Yarn Source: https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md Add pretty-format to your project dependencies using Yarn. ```sh $ yarn add pretty-format ``` -------------------------------- ### Install jest-puppeteer package using npm Source: https://github.com/jestjs/jest/blob/main/docs/Puppeteer.md This command installs the `jest-puppeteer` package as a development dependency. It provides a convenient preset for integrating Jest with Puppeteer, simplifying the setup process for browser-based testing. ```bash npm install --save-dev jest-puppeteer ``` -------------------------------- ### onTestFileStart(test) Source: https://github.com/jestjs/jest/blob/main/packages/jest-reporters/CLAUDE.md Called at the beginning of a test file execution. This method has an alias: onTestStart. ```APIDOC ## Method: `onTestFileStart`\n\n### Description\nCalled at the beginning of a test file execution. This method has an alias: onTestStart.\n\n### Signature\n```typescript\nonTestFileStart?(test): Promise | void;\n```\n\n### Parameters\n- **test** (any) - The test file object being started.\n\n### Returns\n(Promise | void) - A promise that resolves when the operation is complete, or void if synchronous. ``` -------------------------------- ### Directory structure for exact path testing Source: https://github.com/jestjs/jest/blob/main/docs/CLI.md Example file structure containing individual test files. ```bash __tests__ └── t1.test.js # test └── t2.test.js # test ``` -------------------------------- ### Import pretty-format and plugins in JavaScript Source: https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md Demonstrates importing React, react-test-renderer, and pretty-format plugins using CommonJS or ES2015 module syntax. ```javascript // CommonJS const React = require('react'); const renderer = require('react-test-renderer'); const {format: prettyFormat, plugins} = require('pretty-format'); const {ReactElement, ReactTestComponent} = plugins; ``` ```javascript // ES2015 modules and destructuring assignment import React from 'react'; import renderer from 'react-test-renderer'; import {plugins, format as prettyFormat} from 'pretty-format'; const {ReactElement, ReactTestComponent} = plugins; ``` -------------------------------- ### Define sample module for enable automocking example Source: https://github.com/jestjs/jest/blob/main/docs/JestObjectAPI.md Sample module providing functions to demonstrate automocking behavior. ```javascript export default { authorize: () => { return 'token'; }, isAuthorized: secret => secret === 'wizard', }; ``` -------------------------------- ### Configure `babel.config.js` to target current Node.js environment Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md Creates a `babel.config.js` file to configure Babel. It uses `@babel/preset-env` with `targets: {node: 'current'}` to ensure compatibility with the Node.js version running Jest. ```javascript module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; ``` -------------------------------- ### Initialize Jest Configuration Source: https://github.com/jestjs/jest/blob/main/docs/UpgradingToJest30.md Provides commands for initializing a Jest configuration file using `npm`, `yarn`, or `pnpm` after the removal of `jest --init`. ```bash npm init jest@latest ``` ```bash yarn create jest ``` ```bash pnpm create jest ``` -------------------------------- ### Extend NodeEnvironment with custom setup and teardown Source: https://github.com/jestjs/jest/blob/main/docs/TestEnvironment.md Create a custom Node environment class that extends NodeEnvironment, implementing setup/teardown lifecycle methods and handling docblock pragmas. Access config and context in the constructor, and optionally handle test events via handleTestEvent. ```javascript // An example of a custom Node environment const NodeEnvironment = require('jest-environment-node'); /** * @implements {import('jest-environment-node').NodeEnvironment} */ class CustomNodeEnvironment extends NodeEnvironment { constructor(config, context) { super(config, context); console.log(config.globalConfig); console.log(config.projectConfig); this.testPath = context.testPath; this.docblockPragmas = context.docblockPragmas; } async setup() { await super.setup(); await someSetupTasks(this.testPath); this.global.someGlobalObject = createGlobalObject(); // Will trigger if docblock contains @my-custom-pragma my-pragma-value if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') { // ... } } async teardown() { this.global.someGlobalObject = destroyGlobalObject(); await someTeardownTasks(); await super.teardown(); } getVmContext() { return super.getVmContext(); } async handleTestEvent(event, state) { if (event.name === 'test_start') { // ... } } } module.exports = CustomNodeEnvironment; ``` ```typescript // An example of a custom Node environment import NodeEnvironment from 'jest-environment-node'; export default class CustomNodeEnvironment extends NodeEnvironment { constructor(config, context) { super(config, context); console.log(config.globalConfig); console.log(config.projectConfig); this.testPath = context.testPath; this.docblockPragmas = context.docblockPragmas; } async setup() { await super.setup(); await someSetupTasks(this.testPath); this.global.someGlobalObject = createGlobalObject(); // Will trigger if docblock contains @my-custom-pragma my-pragma-value if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') { // ... } } async teardown() { this.global.someGlobalObject = destroyGlobalObject(); await someTeardownTasks(); await super.teardown(); } getVmContext() { return super.getVmContext(); } async handleTestEvent(event, state) { if (event.name === 'test_start') { // ... } } } ``` -------------------------------- ### Disable automatic `babel-jest` transformation in Jest config Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md Modifies `jest.config.js` to explicitly set `transform: {}`. This prevents `babel-jest` from automatically transforming files, useful when you want to define custom transformers or avoid default behavior. ```javascript module.exports = { transform: {}, }; ``` -------------------------------- ### onTestCaseStart(test, info) Source: https://github.com/jestjs/jest/blob/main/packages/jest-reporters/CLAUDE.md Called at the beginning of a single test case execution within a test file. ```APIDOC ## Method: `onTestCaseStart`\n\n### Description\nCalled at the beginning of a single test case execution within a test file.\n\n### Signature\n```typescript\nonTestCaseStart?(test, info): Promise | void;\n```\n\n### Parameters\n- **test** (any) - The test file object containing the test case.\n- **info** (any) - Information about the specific test case.\n\n### Returns\n(Promise | void) - A promise that resolves when the operation is complete, or void if synchronous. ``` -------------------------------- ### Get Project Root and Output JSON Path Source: https://github.com/jestjs/jest/blob/main/packages/jest-phabricator/README.md Helper methods that retrieve the working copy project root directory and construct the path to the output JSON file used for storing test results and coverage data. ```php private function getRoot() { return $this->getWorkingCopy()->getProjectRoot(); } private function getOutputJSON() { return $this->getRoot() . '/output.json'; } ``` -------------------------------- ### describe Group Related Tests Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md Creates a test suite that groups related test cases together. This example organizes tests for a beverage object into a single describe block, improving test organization and readability. ```javascript const myBeverage = { delicious: true, sour: false, }; describe('my beverage', () => { test('is delicious', () => { expect(myBeverage.delicious).toBeTruthy(); }); test('is not sour', () => { expect(myBeverage.sour).toBeFalsy(); }); }); ``` -------------------------------- ### Install source map stack trace formatting in JavaScript Source: https://github.com/jestjs/jest/blob/main/packages/jest-source-map/README.md Replaces Error.prepareStackTrace to map stack frames to original source files using a map registry. Unregistered files fall back to sourceMappingURL comments. ```javascript import {SourceMapSupport} from '@jest/source-map'; const sourceMapSupport = new SourceMapSupport(); sourceMapSupport.install(new Map([['/build/app.js', '/cache/app.js.map']])); new Error('boom').stack; // Error: boom // at greet (/src/app.ts:12:9) ``` -------------------------------- ### POST /jestworker/start Source: https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md Initiates all workers and executes their setup functions. Returns a promise that resolves upon successful worker startup. ```APIDOC ## POST /jestworker/start ### Description Initiates all workers and calls their `setup` function, if defined. This method returns a `Promise` that resolves once all workers are running and their `setup` functions have completed. It is useful for eagerly starting workers. ### Method POST ### Endpoint /jestworker/start ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **status** (string) - Indicates the successful startup of all workers. #### Response Example ```json { "status": "Workers started successfully" } ``` ``` -------------------------------- ### Skip Concurrent Data-Driven Tests with Jest `test.concurrent.skip.each` (Array) Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md This example demonstrates `test.concurrent.skip.each` with an array table to prevent a collection of data-driven tests from running. The specified tests will be marked as skipped, allowing other tests in the suite to execute normally. ```javascript 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); }); ``` -------------------------------- ### Jest Describe and Test Execution Order Source: https://github.com/jestjs/jest/blob/main/docs/SetupAndTeardown.md Demonstrates how Jest executes describe blocks before tests. All console.log statements in describe blocks execute during the collection phase, followed by test execution in order. This shows the importance of using before/after hooks for setup/teardown rather than describe block logic. ```javascript describe('describe outer', () => { console.log('describe outer-a'); describe('describe inner 1', () => { console.log('describe inner 1'); test('test 1', () => console.log('test 1')); }); console.log('describe outer-b'); test('test 2', () => console.log('test 2')); describe('describe inner 2', () => { console.log('describe inner 2'); test('test 3', () => console.log('test 3')); }); console.log('describe outer-c'); }); // Output: // describe outer-a // describe inner 1 // describe outer-b // describe inner 2 // describe outer-c // test 1 // test 2 // test 3 ``` -------------------------------- ### Configure Babel to Use TypeScript Preset in Jest Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This JavaScript configuration snippet for `babel.config.js` adds `@babel/preset-typescript` to the list of Babel presets. This tells Babel to process TypeScript syntax when transpiling files for Jest, allowing TypeScript code to run in the test environment. ```javascript module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], // highlight-next-line '@babel/preset-typescript', ], }; ``` -------------------------------- ### Rendered snapshot output example Source: https://github.com/jestjs/jest/blob/main/docs/Configuration.md Demonstrates the output generated by the custom snapshot serializer plugin. ```json Pretty foo: Object { "x": 1, "y": 2, } ``` -------------------------------- ### Run Jest Benchmark Preparation Script Source: https://github.com/jestjs/jest/blob/main/benchmarks/test-file-overhead/README.md Execute the prepare.sh script to generate necessary benchmark files. On Windows systems, use Bash environments (WSL, Git Bash, or Cygwin) for script execution, though CMD can be used for the actual benchmark run if testing CMD environment performance. ```bash ./prepare.sh ``` -------------------------------- ### describe Nested Test Hierarchies Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md Demonstrates nested describe blocks to organize tests into hierarchical groups. This example tests a binary string conversion function with separate describe blocks for invalid and valid inputs, making test structure more logical. ```javascript 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); }); }); }); ``` -------------------------------- ### Get changed files since a specific branch using getChangedFilesForRoots in JavaScript Source: https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md This JavaScript example shows how to use `getChangedFilesForRoots` to find files that have changed relative to a specific branch, such as 'main'. It imports the function and calls it with root paths and a `changedSince` option, returning a promise with the changed files and repositories. ```javascript import {getChangedFilesForRoots} from 'jest-changed-files'; getChangedFilesForRoots(['/path/to/test'], { changedSince: 'main', }).then(files => { /* { repos: [], changedFiles: [] } */ }); ``` -------------------------------- ### Define data-driven test suite with `describe.each` using array of objects in Jest Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md This example demonstrates `describe.each` using an array of objects for test data. Object properties are destructured in the test function, and test titles are formatted using `$variable` syntax to inject values. ```js 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); }); }); ``` -------------------------------- ### Define data-driven test suite with `describe.each` using array of arrays in Jest Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md This example shows `describe.each` using an array of arrays for test data. Each inner array provides arguments to the test function, and test titles are formatted with `printf` style specifiers like `%i`. ```js describe.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ])('.add(%i, %i)', (a, b, expected) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test(`returned value not be greater than ${expected}`, () => { expect(a + b).not.toBeGreaterThan(expected); }); test(`returned value not be less than ${expected}`, () => { expect(a + b).not.toBeLessThan(expected); }); }); ``` -------------------------------- ### Crawl and list project files with HasteMap in JavaScript Source: https://github.com/jestjs/jest/blob/main/packages/jest-haste-map/README.md Configure and build a HasteMap instance to discover all .js files across available CPU workers. ```javascript import HasteMap from 'jest-haste-map'; import os from 'os'; import {dirname} from 'path'; import {fileURLToPath} from 'url'; const root = dirname(fileURLToPath(import.meta.url)); const map = new HasteMap.default({ id: 'myproject', //Used for caching. extensions: ['js'], // Tells jest-haste-map to only crawl .js files. maxWorkers: os.availableParallelism(), //Parallelizes across all available CPUs. platforms: [], // This is only used for React Native, you can leave it empty. roots: [root], // Can be used to only search a subset of files within `rootDir` retainAllFiles: true, rootDir: root, //The project root. }); const {hasteFS} = await map.build(); const files = hasteFS.getAllFiles(); console.log(files); ``` -------------------------------- ### Import Jest Global APIs in TypeScript Test File Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This TypeScript code demonstrates how to import specific Jest global APIs (like `describe`, `expect`, `test`) from `@jest/globals` into a test file. This approach provides explicit type definitions for these functions, ensuring proper type-checking within TypeScript tests. ```typescript 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); }); }); ``` -------------------------------- ### Use dashed and camelCase argument formats Source: https://github.com/jestjs/jest/blob/main/docs/CLI.md Demonstrates equivalent results when providing CLI options in dashed or camelCase syntax. ```bash jest --collect-coverage jest --collectCoverage ``` -------------------------------- ### Define data-driven test suite with `describe.each` using tagged template literal in Jest Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md This example illustrates `describe.each` with a tagged template literal for test data. The first row defines column headings, and subsequent rows use `${value}`. Test titles use `$variable` to inject data. ```js describe.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `('$a + $b', ({a, b, expected}) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test(`returned value not be greater than ${expected}`, () => { expect(a + b).not.toBeGreaterThan(expected); }); test(`returned value not be less than ${expected}`, () => { expect(a + b).not.toBeLessThan(expected); }); }); ``` -------------------------------- ### Get changed files since last commit using getChangedFilesForRoots in JavaScript Source: https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md This JavaScript example demonstrates how to use `getChangedFilesForRoots` to retrieve files that have changed since the last commit, including ancestor changes. It imports the function and calls it with an array of root paths and options, returning a promise that resolves to an object containing changed files and repositories. ```javascript import {getChangedFilesForRoots} from 'jest-changed-files'; getChangedFilesForRoots(['/path/to/test'], { lastCommit: true, withAncestor: true, }).then(files => { /* { repos: [], changedFiles: [] } */ }); ``` -------------------------------- ### Configure ESLint with eslint-plugin-jest for Global Recognition Source: https://github.com/jestjs/jest/blob/main/docs/GettingStarted.md This JSON configuration for ESLint uses `eslint-plugin-jest` to enable Jest global variables within specific test files. By setting `jest/globals: true` in the `env` section for files matching `tests/**/*`, it allows ESLint to recognize Jest's global APIs and prevent `no-undef` errors. ```json { "overrides": [ { "files": ["tests/**/*"], "plugins": ["jest"], "env": { "jest/globals": true } } ] } ``` -------------------------------- ### Register custom matchers globally in setupFilesAfterEnv Source: https://github.com/jestjs/jest/blob/main/docs/ExpectAPI.md Place expect.extend inside a setupFilesAfterEnv script to make custom matchers available globally without per-file imports. ```javascript import {expect} from '@jest/globals'; // remember to export `toBeWithinRange` as well import {toBeWithinRange} from './toBeWithinRange'; expect.extend({ toBeWithinRange, }); ``` -------------------------------- ### Define Concurrent Data-Driven Tests with Jest `test.concurrent.each` (Tagged Template Literal) Source: https://github.com/jestjs/jest/blob/main/docs/GlobalAPI.md This example shows `test.concurrent.each` utilizing a tagged template literal for data input, enabling named columns and object destructuring in the asynchronous test function. Test titles can inject data using `$variable` syntax. An optional timeout can be specified. ```javascript 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); }); ```