### 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(); }); ``` -------------------------------- ### Configure `setupFilesAfterEnv` in Jest Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Configuration.md This configuration sets the path to a setup file that runs after the test framework is installed, allowing for global setup like extending matchers. ```js const {defineConfig} = require('jest'); module.exports = defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` ```ts import {defineConfig} from 'jest'; export default defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` -------------------------------- ### Configure transformIgnorePatterns for pnpm packages Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Configuration.md This example provides patterns for `transformIgnorePatterns` to correctly handle packages installed via `pnpm`, which uses symlinks under `.pnpm`, allowing specific packages to be transformed. ```js const {defineConfig} = require('jest'); module.exports = defineConfig({ transformIgnorePatterns: [ '/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)', /* if config file is under '~/packages/lib-a/' */ `${path.join( __dirname, '../..', )}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`, /* or using relative pattern to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@x.x.x/node_modules/@scope/pkg-b/' */ 'node_modules/(?!.pnpm|package-a|@scope/pkg-b)', ], }); ``` ```ts import {defineConfig} from 'jest'; export default defineConfig({ transformIgnorePatterns: [ '/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)', /* if config file is under '~/packages/lib-a/' */ `${path.join( __dirname, '../..', )}/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)`, /* or using relative pattern to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@x.x.x/node_modules/@scope/pkg-b/' */ 'node_modules/(?!.pnpm|package-a|@scope/pkg-b)', ], }); ``` -------------------------------- ### 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 ``` -------------------------------- ### Start development server Source: https://github.com/jestjs/jest/blob/main/website/README.md Launches the local Docusaurus server. Alternatively, use yarn workspace jest-website start from the monorepo root. ```bash yarn start ``` -------------------------------- ### 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); }); }); ``` -------------------------------- ### 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(); }); }); ``` -------------------------------- ### Install jest-dynamodb preset Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Define a utility module for `enableAutomock` example Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/JestObjectAPI.md This module provides `authorize` and `isAuthorized` functions, used as dependencies in the `enableAutomock` example. ```javascript export default { authorize: () => { return 'token'; }, isAuthorized: secret => secret === 'wizard', }; ``` -------------------------------- ### Install @babel/preset-env Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Webpack.md Installs the `@babel/preset-env` package as a development dependency, required for Babel configuration with Jest. ```bash npm install --save-dev @babel/preset-env ``` -------------------------------- ### Install Jest via npm Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/GettingStarted.md Install Jest as a development dependency using npm. ```bash npm install --save-dev jest ``` -------------------------------- ### Install Babel TypeScript Preset Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/GettingStarted.md Installs the `@babel/preset-typescript` package to enable Jest to transpile TypeScript files via Babel. ```bash npm install --save-dev @babel/preset-typescript ``` -------------------------------- ### 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(); }); ``` -------------------------------- ### Install jest-mongodb package Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/MongoDB.md Install the @shelf/jest-mongodb package as a dev dependency to enable MongoDB support in Jest. ```bash npm install --save-dev @shelf/jest-mongodb ``` -------------------------------- ### Install ts-jest Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/GettingStarted.md Installs `ts-jest`, a TypeScript preprocessor with source map support, allowing Jest to test projects written in TypeScript. ```bash npm install --save-dev ts-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'; ``` -------------------------------- ### Example File Structure for `runTestsByPath` Source: https://github.com/jestjs/jest/blob/main/docs/CLI.md Illustrates a sample directory structure with test files, used to demonstrate the behavior of the `runTestsByPath` option. ```bash __tests__ └── t1.test.js # test └── t2.test.js # test ``` -------------------------------- ### Example class with static and getter methods Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Es6ClassMocks.md Sample SoundPlayer class demonstrating instance methods, getter methods, and static methods that can be mocked. ```javascript export default class SoundPlayer { constructor() { this.foo = 'bar'; } playSoundFile(fileName) { console.log('Playing sound file ' + fileName); } get foo() { return 'bar'; } static brand() { return 'player-brand'; } } ``` -------------------------------- ### 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. ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Install dependencies Source: https://github.com/jestjs/jest/blob/main/website/README.md Run this command in the root directory to load all project dependencies. Requires Node version 14 or higher. ```bash yarn ``` -------------------------------- ### 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-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 ``` -------------------------------- ### Generate Jest configuration file Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/GettingStarted.md Initialize a basic Jest configuration file by running the setup wizard. ```bash npm init jest@latest ``` -------------------------------- ### Configure Jest Environment with setupFilesAfterEnv Source: https://github.com/jestjs/jest/blob/main/docs/Configuration.md Use this file to set up the testing framework after it's installed but before tests run, allowing for custom matchers or global hooks. ```js const matchers = require('jest-extended'); expect.extend(matchers); afterEach(() => { jest.useRealTimers(); }); ``` -------------------------------- ### 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 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 ``` -------------------------------- ### Respond to File System Changes with `onFileChange` Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/WatchPlugins.md Shows how to implement the `onFileChange` hook to react to file system modifications, receiving information about affected projects. ```javascript class MyWatchPlugin { apply(jestHooks) { jestHooks.onFileChange(({projects}) => { this._projects = projects; }); } } ``` -------------------------------- ### Module for mockImplementation Example (foo.js) Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/MockFunctions.md A simple module that will be mocked to demonstrate the `mockImplementation` method. ```js module.exports = function () { // some implementation; }; ``` -------------------------------- ### Example `createUser` Function with `node-fetch` Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/BypassingModuleMocks.md This asynchronous function demonstrates creating a user by making a POST request using `node-fetch` and extracting the user ID from the response. ```javascript 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; }; ``` -------------------------------- ### Configure setupFilesAfterEnv in Jest Source: https://github.com/jestjs/jest/blob/main/docs/Configuration.md Specifies a list of modules to run after the test framework is installed, such as the `setup-jest.js` file, to apply global configurations. ```js const {defineConfig} = require('jest'); module.exports = defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` ```ts import {defineConfig} from 'jest'; export default defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` -------------------------------- ### Write a test with custom Puppeteer setup Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Puppeteer.md An example Jest test using the __BROWSER_GLOBAL__ object provided by the custom test environment to interact with Puppeteer. ```js const timeout = 5000; describe( '/ (Home Page)', () => { let page; beforeAll(async () => { page = await globalThis.__BROWSER_GLOBAL__.newPage(); await page.goto('https://google.com'); }, timeout); it('should load without error', async () => { const text = await page.evaluate(() => document.body.textContent); expect(text).toContain('google'); }); }, timeout, ); ``` -------------------------------- ### Simulate HTTP request with Promise in JavaScript Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/TutorialAsync.md An example `request.js` module that simulates an HTTP GET request to an API, returning a Promise that resolves with the fetched data. ```js const http = require('http'); export default function request(url) { return new Promise(resolve => { // This is an example of an http request, for example to fetch // user data from an API. // This module is being mocked in __mocks__/request.js http.get({path: url}, response => { let data = ''; response.on('data', _data => (data += _data)); response.on('end', () => resolve(data)); }); }); } ``` -------------------------------- ### 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(); }); ``` -------------------------------- ### Configure transformIgnorePatterns using Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Configuration.md This example demonstrates using the `` token in `transformIgnorePatterns` to ensure patterns correctly resolve relative to the project's root directory, preventing accidental ignoring of files in different environments. ```js const {defineConfig} = require('jest'); module.exports = defineConfig({ transformIgnorePatterns: [ '/bower_components/', '/node_modules/', ], }); ``` ```ts import {defineConfig} from 'jest'; export default defineConfig({ transformIgnorePatterns: [ '/bower_components/', '/node_modules/', ], }); ``` -------------------------------- ### 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. ``` -------------------------------- ### Spy on getter and setter with jest.spyOn() Source: https://github.com/jestjs/jest/blob/main/docs/JestObjectAPI.md Test example showing how to use jest.spyOn() with the 'get' and 'set' accessType parameters to spy on getters and setters. Use jest.restoreAllMocks() in afterEach to clean up spies. ```javascript const audio = require('./audio'); const video = require('./video'); afterEach(() => { // restore the spy created with spyOn jest.restoreAllMocks(); }); test('plays video', () => { const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get' const isPlaying = video.play; expect(spy).toHaveBeenCalled(); expect(isPlaying).toBe(true); }); test('plays audio', () => { const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set' audio.volume = 100; expect(spy).toHaveBeenCalled(); expect(audio.volume).toBe(100); }); ``` -------------------------------- ### Out-of-scope error with non-mock variable in jest.mock() factory Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Es6ClassMocks.md Variables that do not start with 'mock' will cause an out-of-scope error when used in jest.mock() factory functions due to hoisting. This example demonstrates the incorrect pattern. ```javascript // Note: this will fail import SoundPlayer from './sound-player'; const fakePlaySoundFile = jest.fn(); jest.mock('./sound-player', () => { return jest.fn().mockImplementation(() => { return {playSoundFile: fakePlaySoundFile}; }); }); ``` -------------------------------- ### Custom Global Setup for Puppeteer Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/Puppeteer.md Define a global setup script to launch a Puppeteer browser instance and store its WebSocket endpoint for use by test environments. ```js const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); const puppeteer = require('puppeteer'); const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); module.exports = async function () { const browser = await puppeteer.launch(); // store the browser instance so we can teardown it later // this global is only available in the teardown but not in TestEnvironments globalThis.__BROWSER_GLOBAL__ = browser; // use the file system to expose the wsEndpoint for TestEnvironments await mkdir(DIR, {recursive: true}); await writeFile(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint()); }; ``` -------------------------------- ### 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'}}]], }; ``` -------------------------------- ### One-Time Setup with beforeAll and afterAll in Jest Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/SetupAndTeardown.md Use `beforeAll` and `afterAll` to execute setup and teardown logic once before all tests and once after all tests in a file, respectively. This is suitable for expensive operations that can be shared across 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(); }); ``` -------------------------------- ### Explicitly Mocking Modules with jest.doMock and ES6 import Source: https://github.com/jestjs/jest/blob/main/docs/JestObjectAPI.md This example shows how to use `jest.doMock` with ES6 dynamic `import()` for module loading. It requires specifying `__esModule: true` in the mock factory and a Babel setup that supports dynamic imports. ```js beforeEach(() => { jest.resetModules(); }); test('moduleName 1', () => { jest.doMock('../moduleName', () => { return { __esModule: true, default: 'default1', foo: 'foo1' }; }); return import('../moduleName').then(moduleName => { expect(moduleName.default).toBe('default1'); expect(moduleName.foo).toBe('foo1'); }); }); test('moduleName 2', () => { jest.doMock('../moduleName', () => { return { __esModule: true, default: 'default2', foo: 'foo2' }; }); return import('../moduleName').then(moduleName => { expect(moduleName.default).toBe('default2'); expect(moduleName.foo).toBe('foo2'); }); }); ``` -------------------------------- ### 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: {}, }; ``` -------------------------------- ### 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'; } ``` -------------------------------- ### 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. ``` -------------------------------- ### 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 }); ``` -------------------------------- ### 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(); }); }); ``` -------------------------------- ### 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); }); ``` -------------------------------- ### 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', ], }; ``` -------------------------------- ### Set up global state before all tests with `beforeAll` in JavaScript Source: https://github.com/jestjs/jest/blob/main/website/versioned_docs/version-30.4/GlobalAPI.md Use `beforeAll` to set up global state once before any tests run, supporting asynchronous setup by waiting for promises to resolve. ```js const globalDatabase = makeGlobalDatabase(); beforeAll(() => { // Clears the database and adds some testing data. // Jest will wait for this promise to resolve before running tests. return globalDatabase.clear().then(() => { return globalDatabase.insert({testData: 'foo'}); }); }); // Since we only set up the database once in this example, it's important // that our tests don't modify it. test('can find things', () => { return globalDatabase.find('thing', {}, results => { expect(results.length).toBeGreaterThan(0); }); }); ``` -------------------------------- ### 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 all .js files in a project Source: https://github.com/jestjs/jest/blob/main/packages/jest-haste-map/README.md Demonstrates how to configure and build a HasteMap to find all JavaScript files within a specified project root, leveraging parallel processing and caching. ```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); ``` -------------------------------- ### 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: [] } */ }); ```