### Async Repeating Setup with beforeEach Source: https://jestjs.io/docs/next/setup-teardown Handle asynchronous setup operations by returning a promise from `beforeEach`. This ensures that the setup is complete before the test begins execution. ```javascript beforeEach(() => { return initializeCityDatabase(); }); ``` -------------------------------- ### Setup Database Before All Tests Source: https://jestjs.io/docs/next/api Use `beforeAll` to perform asynchronous setup once before any tests in the file run. Jest waits for the returned promise to resolve. Ensure tests do not modify shared state if setup is only done once. ```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); }); }); ``` -------------------------------- ### Install jest-dynamodb Preset Source: https://jestjs.io/docs/next/dynamodb Install the jest-dynamodb preset using your preferred package manager. ```bash npm install --save-dev @shelf/jest-dynamodb ``` ```bash yarn add --dev @shelf/jest-dynamodb ``` ```bash pnpm add --save-dev @shelf/jest-dynamodb ``` ```bash bun add --dev @shelf/jest-dynamodb ``` -------------------------------- ### Complete Test File with Module Factory Mock Source: https://jestjs.io/docs/next/es6-class-mocks A full example demonstrating how to use the module factory parameter with `jest.mock` for class mocking, including setup, cleanup, and assertions for constructor and method calls. ```javascript import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; const mockPlaySoundFile = jest.fn(); jest.mock('./sound-player', () => { return jest.fn().mockImplementation(() => { return {playSoundFile: mockPlaySoundFile}; }); }); beforeEach(() => { SoundPlayer.mockClear(); mockPlaySoundFile.mockClear(); }); it('The consumer should be able to call new() on SoundPlayer', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); // Ensure constructor created the object: expect(soundPlayerConsumer).toBeTruthy(); }); it('We can check if the consumer called the class constructor', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); expect(SoundPlayer).toHaveBeenCalledTimes(1); }); it('We can check if the consumer called a method on the class instance', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); const coolSoundFileName = 'song.mp3'; soundPlayerConsumer.playSomethingCool(); expect(mockPlaySoundFile.mock.calls[0][0]).toBe(coolSoundFileName); }); ``` -------------------------------- ### Install Babel Preset for TypeScript Source: https://jestjs.io/docs/next/getting-started Install the Babel preset for TypeScript using npm, Yarn, pnpm, or Bun. ```bash npm install --save-dev @babel/preset-typescript ``` ```bash yarn add --dev @babel/preset-typescript ``` ```bash pnpm add --save-dev @babel/preset-typescript ``` ```bash bun add --dev @babel/preset-typescript ``` -------------------------------- ### One-Time Setup with beforeAll and afterAll Source: https://jestjs.io/docs/next/setup-teardown Use `beforeAll` and `afterAll` for setup and teardown tasks that only need to be performed once per file. This is efficient for expensive operations that can be reused across all tests in the file. ```javascript 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(); }); ``` -------------------------------- ### Repeating Setup with beforeEach and afterEach Source: https://jestjs.io/docs/next/setup-teardown Use `beforeEach` and `afterEach` to run setup and teardown logic before and after each test in a suite. This is useful for tasks that need to be repeated for multiple tests, such as initializing or clearing a database. ```javascript beforeEach(() => { initializeCityDatabase(); }); afterEach(() => { clearCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); ``` -------------------------------- ### Install jest-puppeteer with Bun Source: https://jestjs.io/docs/next/puppeteer Install the jest-puppeteer package as a development dependency using Bun. ```bash bun add --dev jest-puppeteer ``` -------------------------------- ### Install @shelf/jest-mongodb with Bun Source: https://jestjs.io/docs/next/mongodb Install the jest-mongodb preset using Bun. This package provides the necessary configuration for running Jest tests with MongoDB. ```bash bun add --dev @shelf/jest-mongodb ``` -------------------------------- ### Specify Setup Files with Jest CLI Source: https://jestjs.io/docs/next/cli Use the `--setupFilesAfterEnv` option to provide a list of module paths that will be executed to set up the testing framework before each test. Note that files imported by these setup scripts will not be mocked. ```bash jest --setupFilesAfterEnv ... ``` -------------------------------- ### Import Jest APIs for TypeScript Source: https://jestjs.io/docs/next/mock-function-api When using TypeScript examples from this page, explicitly import Jest APIs to ensure they work as documented. Consult the Getting Started guide for setup details. ```typescript import {expect, jest, test} from '@jest/globals'; ``` -------------------------------- ### Install identity-obj-proxy for CSS Modules Source: https://jestjs.io/docs/next/webpack Install the identity-obj-proxy package to mock CSS Modules in Jest. ```bash npm install --save-dev identity-obj-proxy ``` ```bash yarn add --dev identity-obj-proxy ``` ```bash pnpm add --save-dev identity-obj-proxy ``` ```bash bun add --dev identity-obj-proxy ``` -------------------------------- ### Example createUser function Source: https://jestjs.io/docs/next/bypassing-module-mocks This is the function under test, which uses `node-fetch` to create a user. ```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; }; ``` -------------------------------- ### Install @babel/preset-env for Jest Source: https://jestjs.io/docs/next/webpack Install the necessary Babel preset for Jest to transpile modern JavaScript code. ```bash npm install --save-dev @babel/preset-env ``` ```bash yarn add --dev @babel/preset-env ``` ```bash pnpm add --save-dev @babel/preset-env ``` ```bash bun add --dev @babel/preset-env ``` -------------------------------- ### Example test file with sum function Source: https://jestjs.io/docs/next/configuration An example test file demonstrating a sum function and its test case, intended to be included in code coverage. ```javascript export function sum(a, b) { return a + b; } if (process.env.NODE_ENV === 'test') { test('sum', () => { expect(sum(1, 2)).toBe(3); }); } ``` -------------------------------- ### Install jest-environment-jsdom with Bun Source: https://jestjs.io/docs/next/tutorial-jquery Install the jest-environment-jsdom package using Bun to enable JSDOM testing. ```bash bun add --dev jest-environment-jsdom ``` -------------------------------- ### Install jest-puppeteer with pnpm Source: https://jestjs.io/docs/next/puppeteer Install the jest-puppeteer package as a development dependency using pnpm. ```bash pnpm add --save-dev jest-puppeteer ``` -------------------------------- ### Install Jest Globals Type Definitions Source: https://jestjs.io/docs/next/getting-started Install the Jest globals type definitions using npm, Yarn, pnpm, or Bun. ```bash npm install --save-dev @jest/globals ``` ```bash yarn add --dev @jest/globals ``` ```bash pnpm add --save-dev @jest/globals ``` ```bash bun add --dev @jest/globals ``` -------------------------------- ### Install ts-jest for Jest Source: https://jestjs.io/docs/next/getting-started Install ts-jest, a TypeScript preprocessor for Jest, using npm, Yarn, pnpm, or Bun. ```bash npm install --save-dev ts-jest ``` ```bash yarn add --dev ts-jest ``` ```bash pnpm add --save-dev ts-jest ``` ```bash bun add --dev ts-jest ``` -------------------------------- ### Install @shelf/jest-mongodb with pnpm Source: https://jestjs.io/docs/next/mongodb Install the jest-mongodb preset using pnpm. This package provides the necessary configuration for running Jest tests with MongoDB. ```bash pnpm add --save-dev @shelf/jest-mongodb ``` -------------------------------- ### Install node-notifier for native OS notifications Source: https://jestjs.io/docs/next/configuration To enable native OS notifications for test results, install the 'node-notifier' package. This command installs it as a development dependency. ```bash npm install --save-dev node-notifier ``` ```bash yarn add --dev node-notifier ``` ```bash pnpm add --save-dev node-notifier ``` ```bash bun add --dev node-notifier ``` -------------------------------- ### Install jest-environment-jsdom with pnpm Source: https://jestjs.io/docs/next/tutorial-jquery Install the jest-environment-jsdom package using pnpm to enable JSDOM testing. ```bash pnpm add --save-dev jest-environment-jsdom ``` -------------------------------- ### Install @shelf/jest-mongodb with npm Source: https://jestjs.io/docs/next/mongodb Install the jest-mongodb preset using npm. This package provides the necessary configuration for running Jest tests with MongoDB. ```bash npm install --save-dev @shelf/jest-mongodb ``` -------------------------------- ### Install Jest with Bun Source: https://jestjs.io/docs/next/getting-started Use this command to add Jest as a development dependency in your project using Bun. ```bash bun add --dev jest ``` -------------------------------- ### Install jest-environment-jsdom with npm Source: https://jestjs.io/docs/next/tutorial-jquery Install the jest-environment-jsdom package using npm to enable JSDOM testing. ```bash npm install --save-dev jest-environment-jsdom ``` -------------------------------- ### Install jest-puppeteer with npm Source: https://jestjs.io/docs/next/puppeteer Install the jest-puppeteer package as a development dependency using npm. ```bash npm install --save-dev jest-puppeteer ``` -------------------------------- ### Webpack Configuration Example Source: https://jestjs.io/docs/next/webpack This is a common webpack configuration file that manages JavaScript, CSS, and asset transformations. ```javascript module.exports = { module: { rules: [ { test: /\.jsx?$/, exclude: ['node_modules'], use: ['babel-loader'], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.gif$/, type: 'asset/inline', }, { test: /\.(ttf|eot|svg)$/, type: 'asset/resource', }, ], }, resolve: { alias: { config$: './configs/app-config.js', react: './vendor/react-master', }, extensions: ['.js', '.jsx'], modules: [ 'node_modules', 'bower_components', 'shared', '/shared/vendor/modules', ], }, }; ``` -------------------------------- ### Install jest-puppeteer with Yarn Source: https://jestjs.io/docs/next/puppeteer Install the jest-puppeteer package as a development dependency using Yarn. ```bash yarn add --dev jest-puppeteer ``` -------------------------------- ### Install @shelf/jest-mongodb with Yarn Source: https://jestjs.io/docs/next/mongodb Install the jest-mongodb preset using Yarn. This package provides the necessary configuration for running Jest tests with MongoDB. ```bash yarn add --dev @shelf/jest-mongodb ``` -------------------------------- ### Install jest-environment-jsdom with Yarn Source: https://jestjs.io/docs/next/tutorial-jquery Install the jest-environment-jsdom package using Yarn to enable JSDOM testing. ```bash yarn add --dev jest-environment-jsdom ``` -------------------------------- ### Install @types/jest Package Source: https://jestjs.io/docs/next/getting-started Install the @types/jest package for Jest global type definitions using npm, Yarn, pnpm, or Bun. ```bash npm install --save-dev @types/jest ``` ```bash yarn add --dev @types/jest ``` ```bash pnpm add --save-dev @types/jest ``` ```bash bun add --dev @types/jest ``` -------------------------------- ### Install Babel dependencies for Jest with Bun Source: https://jestjs.io/docs/next/getting-started Install the necessary Babel packages as development dependencies for using Jest with Babel transpilation via Bun. ```bash bun add --dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Install Jest with pnpm Source: https://jestjs.io/docs/next/getting-started Use this command to add Jest as a development dependency in your project using pnpm. ```bash pnpm add --save-dev jest ``` -------------------------------- ### Install Babel dependencies for Jest with pnpm Source: https://jestjs.io/docs/next/getting-started Install the necessary Babel packages as development dependencies for using Jest with Babel transpilation via pnpm. ```bash pnpm add --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Install Jest with npm Source: https://jestjs.io/docs/next/getting-started Use this command to add Jest as a development dependency in your project using npm. ```bash npm install --save-dev jest ``` -------------------------------- ### Install Babel dependencies for Jest with npm Source: https://jestjs.io/docs/next/getting-started Install the necessary Babel packages as development dependencies for using Jest with Babel transpilation via npm. ```bash npm install --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Configure Summary Reporter Options via Default Source: https://jestjs.io/docs/next/configuration Pass options to the 'summary' reporter by configuring the 'default' reporter. This example sets a custom 'summaryThreshold'. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ reporters: [['default', {summaryThreshold: 10}]], }); ``` ```typescript import {defineConfig} from 'jest'; export default defineConfig({ reporters: [['default', {summaryThreshold: 10}]], }); ``` -------------------------------- ### Install Babel dependencies for Jest with Yarn Source: https://jestjs.io/docs/next/getting-started Install the necessary Babel packages as development dependencies for using Jest with Babel transpilation via Yarn. ```bash yarn add --dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Custom Global Setup Module in Jest Source: https://jestjs.io/docs/next/configuration Implement a custom global setup module using `globalSetup`. This module runs once before all test suites and can access Jest's global and project configurations. Globals defined here are not accessible in test suites. ```javascript module.exports = async function (globalConfig, projectConfig) { console.log(globalConfig.testPathPatterns); console.log(projectConfig.cache); // Set reference to mongod in order to close the server during teardown. globalThis.__MONGOD__ = mongod; }; ``` -------------------------------- ### Install Jest with Yarn Source: https://jestjs.io/docs/next/getting-started Use this command to add Jest as a development dependency in your project using Yarn. ```bash yarn add --dev jest ``` -------------------------------- ### Extend NodeEnvironment in TypeScript Source: https://jestjs.io/docs/next/test-environment Extend the NodeEnvironment in TypeScript for custom test environments. This example shows constructor, setup, and teardown overrides. ```typescript 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') { // ... } } } ``` -------------------------------- ### Mock Instances - Example Source: https://jestjs.io/docs/next/mock-function-api The `mock.instances` property is an array containing all object instances created from a mock function using the `new` keyword. ```javascript const mockFn = jest.fn(); const a = new mockFn(); const b = new mockFn(); mockFn.mock.instances[0] === a; // true mockFn.mock.instances[1] === b; // true ``` -------------------------------- ### Handle Test Run Completion Source: https://jestjs.io/docs/next/watch-plugins Shows how to use the `onTestRunComplete` hook to access test results, for example, to track snapshot failures. ```javascript class MyWatchPlugin { apply(jestHooks) { jestHooks.onTestRunComplete(results => { this._hasSnapshotFailure = results.snapshot.failure; }); } } ``` -------------------------------- ### Configure moduleDirectories in Jest (JavaScript) Source: https://jestjs.io/docs/next/configuration Specify an array of directory names to be searched recursively for modules. This example includes both `node_modules` and `bower_components` in the search path. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ moduleDirectories: ['node_modules', 'bower_components'], }); ``` -------------------------------- ### React to File System Changes Source: https://jestjs.io/docs/next/watch-plugins Demonstrates using the `onFileChange` hook to capture information about projects and their watched test paths when file system changes are detected. ```javascript class MyWatchPlugin { apply(jestHooks) { jestHooks.onFileChange(({projects}) => { this._projects = projects; }); } } ``` -------------------------------- ### Generate Jest configuration with Bun Source: https://jestjs.io/docs/next/getting-started Initialize Jest configuration by running this command with Bun. Jest will prompt you for project-specific settings. ```bash bunx create-jest ``` -------------------------------- ### Define a Custom Jest Environment (JavaScript) Source: https://jestjs.io/docs/next/configuration Implement a custom Jest environment by extending the JestEnvironment interface. This JavaScript example shows the basic structure for a custom environment. ```javascript /** * @implements {import('@jest/environment').JestEnvironment} */ class CustomEnvironment { constructor(config, context) { const {projectConfig} = config; // Implement the constructor } // Example of a method getVmContext() { return null; } // Implement the required methods here } module.exports = CustomEnvironment; ``` -------------------------------- ### Custom Reporter Class Implementation Source: https://jestjs.io/docs/next/configuration Example of a custom Jest reporter class. It accepts global configuration, reporter options, and context, and implements the `onRunComplete` hook. ```javascript class CustomReporter { constructor(globalConfig, reporterOptions, reporterContext) { this._globalConfig = globalConfig; this._options = reporterOptions; this._context = reporterContext; } onRunComplete(testContexts, results) { console.log('Custom reporter output:'); console.log('global config:', this._globalConfig); console.log('options for this reporter from Jest config:', this._options); console.log('reporter context passed from test scheduler:', this._context); } getLastError() { if (this._shouldFail) { return new Error('Custom error reported!'); } } } module.exports = CustomReporter; ``` -------------------------------- ### Scaffolding Jest Configuration Source: https://jestjs.io/docs/next/upgrading-to-jest30 The interactive `jest --init` command has been removed. Use `npm`, `yarn`, or `pnpm` with the `create jest` command to scaffold a new Jest configuration file. ```bash npm init jest@latest ``` ```bash yarn create jest ``` ```bash pnpm create jest ``` -------------------------------- ### Generate Jest configuration with npm Source: https://jestjs.io/docs/next/getting-started Initialize Jest configuration by running this command with npm. Jest will prompt you for project-specific settings. ```bash npm init jest@latest ``` -------------------------------- ### Execute Plugin Logic on Key Press Source: https://jestjs.io/docs/next/watch-plugins Shows how to implement the `run` method to execute custom logic when the associated key is pressed in watch mode. It also demonstrates how to trigger a test run using `updateConfigAndRun`. ```javascript class MyWatchPlugin { run(globalConfig, updateConfigAndRun) { // do something. } } ``` -------------------------------- ### Configure setupFilesAfterEnv in Jest Source: https://jestjs.io/docs/next/configuration Use setupFilesAfterEnv to run code after the test framework is installed but before tests execute. This is useful for extending Jest with custom matchers or setting up global state. ```javascript const matchers = require('jest-extended'); expect.extend(matchers); afterEach(() => { jest.useRealTimers(); }); ``` ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` ```typescript import {defineConfig} from 'jest'; export default defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` -------------------------------- ### Global Setup Script for Puppeteer Source: https://jestjs.io/docs/next/puppeteer Launches a Puppeteer browser instance and exposes its WebSocket endpoint via the file system for use in test environments. This script runs once before all tests. ```javascript 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(); globalThis.__BROWSER_GLOBAL__ = browser; await mkdir(DIR, {recursive: true}); await writeFile(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint()); }; ``` -------------------------------- ### Define Watch Menu Prompt Source: https://jestjs.io/docs/next/watch-plugins Illustrates how to implement `getUsageInfo` to add a custom key and prompt to the watch mode menu, allowing users to trigger plugin actions. ```javascript class MyWatchPlugin { getUsageInfo(globalConfig) { return { key: 's', prompt: 'do something', }; } } ``` -------------------------------- ### Import Manual Mock Before Tested File Source: https://jestjs.io/docs/next/manual-mocks If `window.matchMedia()` is executed directly in the file under test, import your manual mock file before the tested file to ensure the mock is applied. ```javascript import './matchMedia.mock'; // Must be imported before the tested file import {myMethod} from './file-to-test'; describe('myMethod()', () => { // Test the method here... }); ``` -------------------------------- ### Generate Jest configuration with pnpm Source: https://jestjs.io/docs/next/getting-started Initialize Jest configuration by running this command with pnpm. Jest will prompt you for project-specific settings. ```bash pnpm create jest ``` -------------------------------- ### Example Snapshot Artifact Source: https://jestjs.io/docs/next/snapshot-testing This is an example of a Jest snapshot file generated for a React component. It represents the serializable output of the component during a test run. ```javascript exports["renders correctly 1"] = " Facebook "; ``` -------------------------------- ### Extend NodeEnvironment in JavaScript Source: https://jestjs.io/docs/next/test-environment Extend the NodeEnvironment to add custom setup, teardown, or global objects. Access test path and docblock pragmas in the constructor and setup. ```javascript 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; ``` -------------------------------- ### Inspect Mock Instances and Contexts Source: https://jestjs.io/docs/next/mock-functions Demonstrates how to use the `.mock.instances` and `.mock.contexts` properties to inspect the `this` context and instances created by mock functions. ```javascript const myMock1 = jest.fn(); const a = new myMock1(); console.log(myMock1.mock.instances); // > [ ] const myMock2 = jest.fn(); const b = {}; const bound = myMock2.bind(b); bound(); console.log(myMock2.mock.contexts); // > [ ] ``` -------------------------------- ### Jest Configuration for Custom Puppeteer Setup Source: https://jestjs.io/docs/next/puppeteer Configures Jest to use the custom global setup, global teardown, and test environment scripts for Puppeteer integration. This replaces the need for the jest-puppeteer preset. ```javascript module.exports = { globalSetup: './setup.js', globalTeardown: './teardown.js', testEnvironment: './puppeteer_environment.js', }; ``` -------------------------------- ### Automock Example for Utilities Source: https://jestjs.io/docs/next/configuration This example demonstrates how Jest automatically mocks imported modules when the `automock` option is enabled. It shows how to assert that module methods are mocks and how to provide custom return values. ```javascript export default { authorize: () => 'token', isAuthorized: secret => secret === 'wizard', }; ``` ```javascript import utils from '../utils'; test('if utils mocked automatically', () => { // Public methods of `utils` are now mock functions expect(utils.authorize.mock).toBeTruthy(); expect(utils.isAuthorized.mock).toBeTruthy(); // You can provide them with your own implementation // or pass the expected return value utils.authorize.mockReturnValue('mocked_token'); utils.isAuthorized.mockReturnValue(true); expect(utils.authorize()).toBe('mocked_token'); expect(utils.isAuthorized('not_wizard')).toBeTruthy(); }); ``` -------------------------------- ### Run Jest from command line with options Source: https://jestjs.io/docs/next/getting-started Execute Jest tests matching a pattern, using a specific configuration file, and enabling OS notifications upon completion. ```bash jest my-test --notify --config=config.json ``` -------------------------------- ### run(globalConfig, updateConfigAndRun) Source: https://jestjs.io/docs/next/watch-plugins Handle the execution of your custom watch command when the associated key is pressed. ```APIDOC ### `run(globalConfig, updateConfigAndRun)` This method is executed when the user presses the key defined in `getUsageInfo`. It allows you to perform custom actions and control whether Jest should rerun tests afterward. - **`globalConfig`** (object) - Jest's global configuration object. - **`updateConfigAndRun`** (function) - A function that can be called to trigger a test run with updated configuration. **Returns:** - **`Promise`** - A promise that resolves to a boolean. `true` indicates that Jest should rerun tests after the plugin finishes, `false` otherwise. **Example:** ```javascript run(globalConfig, updateConfigAndRun) { console.log('Running custom action...'); // Perform some custom logic here // Optionally, trigger a test run with updated configuration // updateConfigAndRun({ changedSince: 'lastCommit' }); // Resolve to false if updateConfigAndRun was called to avoid double runs return Promise.resolve(false); } ``` **Note:** If you call `updateConfigAndRun`, ensure your `run` method resolves to `false` to prevent Jest from running tests twice. ``` -------------------------------- ### Mocking with Module Factory - ReferenceError Example Source: https://jestjs.io/docs/next/es6-class-mocks This example illustrates a `ReferenceError` when the mock is not wrapped in an arrow function, causing it to be accessed before initialization after hoisting. Ensure your module factory returns a function or a mock function that can be called. ```javascript import SoundPlayer from './sound-player'; const mockSoundPlayer = jest.fn().mockImplementation(() => { return {playSoundFile: mockPlaySoundFile}; }); // results in a ReferenceError jest.mock('./sound-player', () => { return mockSoundPlayer; }); ``` -------------------------------- ### Basic Jest Configuration (JavaScript) Source: https://jestjs.io/docs/next/configuration Use `defineConfig` from 'jest' to create a basic JavaScript configuration file. Specify your options within the returned object. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ // ... Specify options here. }); ``` -------------------------------- ### Mocking with Module Factory - Out-of-Scope Error Example Source: https://jestjs.io/docs/next/es6-class-mocks This example demonstrates an out-of-scope error that occurs when trying to use a variable not prefixed with 'mock' within the module factory. Jest hoists `jest.mock` calls, preventing access to variables defined after the mock declaration. ```javascript // Note: this will fail import SoundPlayer from './sound-player'; const fakePlaySoundFile = jest.fn(); jest.mock('./sound-player', () => { return jest.fn().mockImplementation(() => { return {playSoundFile: fakePlaySoundFile}; }); }); ``` -------------------------------- ### Generate Jest configuration with Yarn Source: https://jestjs.io/docs/next/getting-started Initialize Jest configuration by running this command with Yarn. Jest will prompt you for project-specific settings. ```bash yarn create jest ``` -------------------------------- ### jest.useRealTimers() Source: https://jestjs.io/docs/next/jest-object Installs real timers. This restores the default behavior of timers. ```APIDOC ## jest.useRealTimers() ### Description Installs real timers. This restores the default behavior of timers. ### Returns The `jest` object for chaining. ``` -------------------------------- ### jest.useFakeTimers(fakeTimersConfig?) Source: https://jestjs.io/docs/next/jest-object Installs fake timers. This allows you to control the passage of time in your tests. ```APIDOC ## jest.useFakeTimers(fakeTimersConfig?) ### Description Installs fake timers. This allows you to control the passage of time in your tests. ### Parameters #### Path Parameters - **fakeTimersConfig** (object) - Optional - Configuration options for the fake timers. ### Returns The `jest` object for chaining. ``` -------------------------------- ### Include project root for ignore patterns Source: https://jestjs.io/docs/next/configuration Use the `` token to ensure that `transformIgnorePatterns` correctly targets directories like `bower_components` and `node_modules` relative to the project's root, regardless of the environment's root directory. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ transformIgnorePatterns: [ '/bower_components/', '/node_modules/', ], }); ``` ```typescript import {defineConfig} from 'jest'; export default defineConfig({ transformIgnorePatterns: [ '/bower_components/', '/node_modules/', ], }); ``` -------------------------------- ### React Native Component for Snapshot Testing Source: https://jestjs.io/docs/next/tutorial-react-native An example React Native component 'Intro' with basic views and text, suitable for snapshot testing. This code defines the UI structure and styles. ```javascript 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; ``` -------------------------------- ### Display Jest Configuration with CLI Source: https://jestjs.io/docs/next/cli Use the `--showConfig` option to print the current Jest configuration to the console and then exit. ```bash jest --showConfig ``` -------------------------------- ### Configure Multiple Projects (JS) Source: https://jestjs.io/docs/next/configuration Use the 'projects' option to run tests in multiple directories or glob patterns simultaneously, ideal for monorepos. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ projects: ['', '/examples/*'], }); ``` -------------------------------- ### Custom Sequencer Implementation Source: https://jestjs.io/docs/next/configuration Example implementation of a custom Jest test sequencer. It includes methods for sharding and sorting tests. ```javascript const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { /** * Select tests for shard requested via --shard=shardIndex/shardCount * Sharding is applied before sorting */ shard(tests, {shardIndex, shardCount}) { const shardSize = Math.ceil(tests.length / shardCount); const shardStart = shardSize * (shardIndex - 1); const shardEnd = shardSize * shardIndex; return [...tests] .sort((a, b) => (a.path > b.path ? 1 : -1)) .slice(shardStart, shardEnd); } /** * Sort test to determine order of execution * Sorting is applied after sharding */ sort(tests) { // Test structure information // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = [...tests]; return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } } module.exports = CustomSequencer; ``` -------------------------------- ### Get Type of Value with jest-get-type Source: https://jestjs.io/docs/next/jest-platform The `getType` function from `@jest/get-type` identifies the primitive type of any JavaScript value, returning it as a string. ```javascript const {getType} = require('@jest/get-type'); const array = [1, 2, 3]; const nullValue = null; const undefinedValue = undefined; // prints 'array' console.log(getType(array)); // prints 'null' console.log(getType(nullValue)); // prints 'undefined' console.log(getType(undefinedValue)); ``` -------------------------------- ### describe.each(table)(name, fn, timeout) Source: https://jestjs.io/docs/next/api Creates a parameterized test suite. The `table` can be an array of arrays or an array of objects, allowing you to run the same test logic with different sets of data. ```APIDOC ## describe.each(table)(name, fn, timeout) ### Description Creates a parameterized test suite. The `table` can be an array of arrays or an array of objects, allowing you to run the same test logic with different sets of data. ### Parameters - **table** (array) - An array of arrays or objects representing the test data. - **name** (string) - The name of the test suite, which can include placeholders for table values. - **fn** (function) - The test function that will be executed for each row of the table. - **timeout** (number) - Optional timeout in milliseconds. ``` -------------------------------- ### Use Summary Reporter Standalone Source: https://jestjs.io/docs/next/configuration Configure Jest to use the 'jest-silent-reporter' and 'summary' reporters. This setup is useful for custom reporting needs. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ reporters: ['jest-silent-reporter', 'summary'], }); ``` ```typescript import {defineConfig} from 'jest'; export default defineConfig({ reporters: ['jest-silent-reporter', 'summary'], }); ``` -------------------------------- ### Configure Multiple Projects with Different Runners (JS) Source: https://jestjs.io/docs/next/configuration Configure multiple projects with different display names and runners, such as running tests and ESLint in the same invocation. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ projects: [ { displayName: 'test', }, { displayName: 'lint', runner: 'jest-runner-eslint', testMatch: ['/**/*.js'], }, ], }); ``` -------------------------------- ### Get Mock Implementation - JavaScript Source: https://jestjs.io/docs/next/mock-function-api Retrieves the current implementation of a mock function set by `mockImplementation()`. Returns `undefined` if no implementation has been set. ```javascript const mockFn = jest.fn(); mockFn.getMockImplementation(); // undefined mockFn.mockImplementation(() => 42); mockFn.getMockImplementation(); // () => 42 ``` -------------------------------- ### Test asynchronous functionality with async/await Source: https://jestjs.io/docs/next/tutorial-async Demonstrates testing asynchronous functions using the `async`/`await` syntax for improved readability. This approach allows writing asynchronous code that looks synchronous. ```javascript // async/await can be used. it('works with async/await', async () => { expect.assertions(1); const data = await user.getUserName(4); expect(data).toBe('Mark'); }); // async/await can also be used with `.resolves`. it('works with async/await and resolves', async () => { expect.assertions(1); await expect(user.getUserName(5)).resolves.toBe('Paul'); }); ``` -------------------------------- ### Jest Transform Configuration with Babel Source: https://jestjs.io/docs/next/webpack Example of configuring Jest's 'transform' option to include the default babel-jest transformer alongside other preprocessors. ```json "transform": { "\.[jt]sx?": "babel-jest", "\.css$": "some-css-transformer", } ``` -------------------------------- ### Extend Jest Built-in Environment Source: https://jestjs.io/docs/next/test-environment Example of extending a built-in Jest environment. This is useful for setting up custom global variables or mocks for your tests. ```javascript const { JestEnvironment } = require('jest-environment-node'); module.exports = class MyEnvironment extends JestEnvironment { constructor(config, options) { super(config, options); } async setup() { await super.setup(); // Add custom setup logic here this.global.myCustomGlobal = 'hello'; } async teardown() { // Add custom teardown logic here await super.teardown(); } runScript(script) { return super.runScript(script); } }; ``` -------------------------------- ### Run Jest via Bun with CLI Arguments Source: https://jestjs.io/docs/next/cli Demonstrates how to pass Jest CLI arguments when running tests using Bun. Arguments are appended directly after the test script. ```bash bun run test -u -t "ColorPicker" ``` -------------------------------- ### Validate Configuration with jest-validate Source: https://jestjs.io/docs/next/jest-platform Use `validate` to check user configurations against an example. It returns an object indicating if there are deprecation warnings and if the configuration is valid. ```javascript const {validate} = require('jest-validate'); const configByUser = { transform: '/node_modules/my-custom-transform', }; const result = validate(configByUser, { comment: ' Documentation: http://custom-docs.com', exampleConfig: {transform: '/node_modules/babel-jest'}, }); console.log(result); ``` -------------------------------- ### Retrieving Last Call Arguments of a Mock Function Source: https://jestjs.io/docs/next/mock-function-api Get the arguments from the most recent invocation of a mock function. Returns `undefined` if the mock has not been called. ```javascript ['arg3', 'arg4']; ``` -------------------------------- ### test.todo Source: https://jestjs.io/docs/next/api Marks a test as to be implemented later, highlighting it in the summary output. ```APIDOC ## test.todo(name) ### Description 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. ### Alias `it.todo(name)` ### Example ```javascript 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` instead, if you already implemented the test, but do not want it to run. ``` -------------------------------- ### Get Changed Files with jest-changed-files Source: https://jestjs.io/docs/next/jest-platform Use `getChangedFilesForRoots` to find modified files since the last commit. Requires specifying the root directory. ```javascript const {getChangedFilesForRoots} = require('jest-changed-files'); // print the set of modified files since last commit in the current repo getChangedFilesForRoots(['./'], { lastCommit: true, }).then(result => console.log(result.changedFiles)); ```