### Initialize Jest Project with Bun Source: https://jestjs.io/docs/30.0/getting-started Use this command to initialize a new Jest project with Bun. Jest will guide you through the setup process. ```bash bunx create-jest ``` -------------------------------- ### Initialize Jest Project with npm Source: https://jestjs.io/docs/30.0/getting-started Use this command to initialize a new Jest project with npm. Jest will guide you through the setup process. ```bash npm init jest@latest ``` -------------------------------- ### Initialize Jest Project with pnpm Source: https://jestjs.io/docs/30.0/getting-started Use this command to initialize a new Jest project with pnpm. Jest will guide you through the setup process. ```bash pnpm create jest ``` -------------------------------- ### Example package.json for Jest React Setup Source: https://jestjs.io/docs/30.0/tutorial-react Configures project dependencies, development dependencies, and test scripts for a React project using Jest. Ensure versions are up-to-date. ```json { "dependencies": { "react": "", "react-dom": "" }, "devDependencies": { "@babel/preset-env": "", "@babel/preset-react": "", "babel-jest": "", "jest": "", "react-test-renderer": "" }, "scripts": { "test": "jest" } } ``` -------------------------------- ### Initialize Jest Project with Yarn Source: https://jestjs.io/docs/30.0/getting-started Use this command to initialize a new Jest project with Yarn. Jest will guide you through the setup process. ```bash yarn create jest ``` -------------------------------- ### Configure Jest Setup Files Source: https://jestjs.io/docs/30.0/configuration Use `setupFilesAfterEnv` to run code after the test framework is installed but before tests execute. This is useful for adding custom matchers or setting up global state. ```javascript const matchers = require('jest-extended'); expect.extend(matchers); afterEach(() => { jest.useRealTimers(); }); ``` ```javascript /** @type {import('jest').Config} */ const config = { setupFilesAfterEnv: ['/setup-jest.js'], }; module.exports = config; ``` ```typescript import type {Config} from 'jest'; const config: Config = { setupFilesAfterEnv: ['/setup-jest.js'], }; export default config; ``` -------------------------------- ### Install @testing-library/react with Bun Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package as a development dependency using Bun. ```bash bun add --dev @testing-library/react ``` -------------------------------- ### Install jest-dynamodb Preset (Bun) Source: https://jestjs.io/docs/30.0/dynamodb Install the jest-dynamodb preset using Bun. ```bash bun add --dev @shelf/jest-dynamodb ``` -------------------------------- ### Install @testing-library/react with npm Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package as a development dependency using npm. ```bash npm install --save-dev @testing-library/react ``` -------------------------------- ### Install jest-mongodb Preset with Bun Source: https://jestjs.io/docs/30.0/mongodb Install the `@shelf/jest-mongodb` package as a development dependency using Bun. ```bash bun add --dev @shelf/jest-mongodb ``` -------------------------------- ### Install jest-dynamodb Preset (npm) Source: https://jestjs.io/docs/30.0/dynamodb Install the jest-dynamodb preset using npm. ```bash npm install --save-dev @shelf/jest-dynamodb ``` -------------------------------- ### Install jest-dynamodb Preset (Yarn) Source: https://jestjs.io/docs/30.0/dynamodb Install the jest-dynamodb preset using Yarn. ```bash yarn add --dev @shelf/jest-dynamodb ``` -------------------------------- ### Install jest-dynamodb Preset (pnpm) Source: https://jestjs.io/docs/30.0/dynamodb Install the jest-dynamodb preset using pnpm. ```bash pnpm add --save-dev @shelf/jest-dynamodb ``` -------------------------------- ### Install @testing-library/react with Yarn Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package as a development dependency using Yarn. ```bash yarn add --dev @testing-library/react ``` -------------------------------- ### Install @testing-library/react with pnpm Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package as a development dependency using pnpm. ```bash pnpm add --save-dev @testing-library/react ``` -------------------------------- ### One-Time Setup with beforeAll and afterAll Source: https://jestjs.io/docs/30.0/setup-teardown Use `beforeAll` and `afterAll` for setup and teardown logic that only needs to run once per file. This is useful for asynchronous operations that initialize or clean up resources shared across multiple tests. ```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 and Teardown with beforeEach and afterEach Source: https://jestjs.io/docs/30.0/setup-teardown Use `beforeEach` and `afterEach` to run setup and cleanup code before and after each test in a suite. This is useful for tasks like initializing or clearing a database for multiple tests. ```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(); }); ``` -------------------------------- ### Run setup before all tests with beforeAll Source: https://jestjs.io/docs/30.0/api Use `beforeAll` to execute setup logic once before any tests in a file begin. Jest waits for promises returned by `beforeAll` to resolve, enabling asynchronous setup. This is ideal for initializing shared global state. ```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); }); }); ``` -------------------------------- ### Complete ES6 Class Mock Example Source: https://jestjs.io/docs/30.0/es6-class-mocks This example demonstrates a full test file using `jest.mock` with a module factory to mock an ES6 class. It covers mocking the constructor and instance methods, and includes setup for clearing mocks between tests. ```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(); 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 jest-mongodb Preset with pnpm Source: https://jestjs.io/docs/30.0/mongodb Install the `@shelf/jest-mongodb` package as a development dependency using pnpm. ```bash pnpm add --save-dev @shelf/jest-mongodb ``` -------------------------------- ### Install @babel/preset-env with Bun Source: https://jestjs.io/docs/30.0/webpack Install the necessary Babel preset for Jest when using webpack. ```bash bun add --dev @babel/preset-env ``` -------------------------------- ### Setup with beforeEach Source: https://jestjs.io/docs/30.0/api Use beforeEach to reset global state or perform setup before each test. Jest waits for promises returned by beforeEach. ```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-mongodb Preset with npm Source: https://jestjs.io/docs/30.0/mongodb Install the `@shelf/jest-mongodb` package as a development dependency using npm. ```bash npm install --save-dev @shelf/jest-mongodb ``` -------------------------------- ### Install @babel/preset-env with pnpm Source: https://jestjs.io/docs/30.0/webpack Install the necessary Babel preset for Jest when using webpack. ```bash pnpm add --save-dev @babel/preset-env ``` -------------------------------- ### Asynchronous Setup with beforeEach and Promises Source: https://jestjs.io/docs/30.0/setup-teardown Handle asynchronous setup operations by returning a promise from `beforeEach`. Jest will wait for the promise to resolve before running the tests. ```javascript beforeEach(() => { return initializeCityDatabase(); }); ``` -------------------------------- ### Basic transformIgnorePatterns Configuration (JavaScript) Source: https://jestjs.io/docs/30.0/configuration Configure `transformIgnorePatterns` to exclude specific directories from transformation. This example shows a common setup for JavaScript projects. ```javascript /** @type {import('jest').Config} */ const config = { transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'], }; module.exports = config; ``` -------------------------------- ### Example createUser.js function Source: https://jestjs.io/docs/30.0/bypassing-module-mocks This is the example function that makes a POST request using `node-fetch` and returns the user ID. ```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 jest-mongodb Preset with Yarn Source: https://jestjs.io/docs/30.0/mongodb Install the `@shelf/jest-mongodb` package as a development dependency using Yarn. ```bash yarn add --dev @shelf/jest-mongodb ``` -------------------------------- ### Install identity-obj-proxy for CSS Modules Source: https://jestjs.io/docs/30.0/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 ``` -------------------------------- ### Install @babel/preset-env with npm Source: https://jestjs.io/docs/30.0/webpack Install the necessary Babel preset for Jest when using webpack. ```bash npm install --save-dev @babel/preset-env ``` -------------------------------- ### Install @babel/preset-env with Yarn Source: https://jestjs.io/docs/30.0/webpack Install the necessary Babel preset for Jest when using webpack. ```bash yarn add --dev @babel/preset-env ``` -------------------------------- ### Install Jest and React Testing Dependencies (npm) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest and necessary Babel and React testing packages using npm. This is a required step for setting up Jest for React projects. ```bash npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Webpack Configuration Example Source: https://jestjs.io/docs/30.0/webpack A typical webpack configuration file demonstrating module rules for JavaScript, CSS, and assets, along with resolve configurations. ```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 and React Testing Dependencies (Bun) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest and necessary Babel and React testing packages using Bun. Bun is a fast JavaScript runtime and package manager. ```bash bun add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Install Babel Dependencies with Bun Source: https://jestjs.io/docs/30.0/getting-started Install the necessary Babel dependencies for Jest using Bun. This includes babel-jest, @babel/core, and @babel/preset-env. ```bash bun add --dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Async Matchers Example Source: https://jestjs.io/docs/30.0/expect Demonstrates how to implement and use an asynchronous custom matcher that fetches external data. ```APIDOC ## Async Matchers `expect.extend` supports asynchronous matchers. These matchers return a Promise and require `await`. ### Example: `toBeDivisibleByExternalValue` This matcher checks if a received number is divisible by a value fetched from an external source. ```javascript expect.extend({ async toBeDivisibleByExternalValue(received) { const externalValue = await getExternalValueFromRemoteSource(); const pass = received % externalValue === 0; if (pass) { return { message: () => `expected ${received} not to be divisible by ${externalValue}`, pass: true, }; } return { message: () => `expected ${received} to be divisible by ${externalValue}`, pass: false, }; }, }); test('is divisible by external value', async () => { await expect(100).toBeDivisibleByExternalValue(); await expect(101).not.toBeDivisibleByExternalValue(); }); ``` ``` -------------------------------- ### Install Jest with Bun Source: https://jestjs.io/docs/30.0/getting-started Use this command to add Jest as a development dependency in your project using Bun. ```bash bun add --dev jest ``` -------------------------------- ### Install jest-puppeteer with Bun Source: https://jestjs.io/docs/30.0/puppeteer Install the jest-puppeteer package using Bun. This package facilitates the integration of Jest with Puppeteer for testing. ```bash bun add --dev jest-puppeteer ``` -------------------------------- ### Install Babel Dependencies with npm Source: https://jestjs.io/docs/30.0/getting-started Install the necessary Babel dependencies for Jest using npm. This includes babel-jest, @babel/core, and @babel/preset-env. ```bash npm install --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Install node-notifier for Notifications Source: https://jestjs.io/docs/30.0/configuration To enable native OS notifications for test results, install the `node-notifier` package using your preferred package manager. ```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 @types/jest for Jest Type Definitions Source: https://jestjs.io/docs/30.0/getting-started Install the `@types/jest` package to provide type definitions for Jest globals. This avoids the need to import them explicitly and offers type safety. ```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 with pnpm Source: https://jestjs.io/docs/30.0/getting-started Install the necessary Babel dependencies for Jest using pnpm. This includes babel-jest, @babel/core, and @babel/preset-env. ```bash pnpm add --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Global Setup Script for Puppeteer Source: https://jestjs.io/docs/30.0/puppeteer This script launches a Puppeteer browser instance and exposes its WebSocket endpoint via the file system. This is part of a custom setup for integrating Puppeteer with Jest. ```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(); // 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()); }; ``` -------------------------------- ### Jest Setup and Teardown Hook Order Source: https://jestjs.io/docs/30.0/setup-teardown Demonstrates the execution order of beforeEach and afterEach hooks, including nested describe blocks. ```javascript beforeEach(() => console.log('connection setup')); beforeEach(() => console.log('database setup')); afterEach(() => console.log('database teardown')); afterEach(() => console.log('connection teardown')); test('test 1', () => console.log('test 1')); describe('extra', () => { beforeEach(() => console.log('extra database setup')); afterEach(() => console.log('extra database teardown')); test('test 2', () => console.log('test 2')); }); // connection setup // database setup // test 1 // database teardown // connection teardown // connection setup // database setup // extra database setup // test 2 // extra database teardown // database teardown // connection teardown ``` -------------------------------- ### Install Jest with pnpm Source: https://jestjs.io/docs/30.0/getting-started Use this command to add Jest as a development dependency in your project using pnpm. ```bash pnpm add --save-dev jest ``` -------------------------------- ### Install Jest and React Testing Dependencies (Yarn) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest and necessary Babel and React testing packages using Yarn. This is an alternative to npm for managing project dependencies. ```bash yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Install ts-jest for TypeScript Preprocessing Source: https://jestjs.io/docs/30.0/getting-started Install `ts-jest`, a TypeScript preprocessor for Jest, using npm, Yarn, pnpm, or Bun. This allows Jest to directly process TypeScript files. ```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 ``` -------------------------------- ### Scoped Setup with beforeEach within describe Source: https://jestjs.io/docs/30.0/setup-teardown Hooks declared inside a `describe` block apply only to tests within that block. This allows for different setup and teardown logic for distinct groups of tests, as shown with `initializeFoodDatabase`. ```javascript // Applies to all tests in this file beforeEach(() => { return initializeCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); describe('matching cities to foods', () => { // Applies only to tests in this describe block beforeEach(() => { return initializeFoodDatabase(); }); test('Vienna <3 veal', () => { expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true); }); test('San Juan <3 plantains', () => { expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true); }); }); ``` -------------------------------- ### Install Babel Preset for TypeScript Source: https://jestjs.io/docs/30.0/getting-started Install the Babel preset for TypeScript using npm, Yarn, pnpm, or Bun. This is required for Jest to transpile TypeScript code via Babel. ```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 ``` -------------------------------- ### Install Jest and React Testing Dependencies (pnpm) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest and necessary Babel and React testing packages using pnpm. This is another package manager option for Node.js projects. ```bash pnpm add --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Install jest-environment-jsdom with Bun Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the JSDOM test environment for Jest using Bun. This package is required to simulate a browser DOM in your tests. ```bash bun add --dev jest-environment-jsdom ``` -------------------------------- ### Install Jest with npm Source: https://jestjs.io/docs/30.0/getting-started Use this command to add Jest as a development dependency in your project using npm. ```bash npm install --save-dev jest ``` -------------------------------- ### Install jest-environment-jsdom with pnpm Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the JSDOM test environment for Jest using pnpm. This package is required to simulate a browser DOM in your tests. ```bash pnpm add --save-dev jest-environment-jsdom ``` -------------------------------- ### Install jest-puppeteer with Yarn Source: https://jestjs.io/docs/30.0/puppeteer Install the jest-puppeteer package using Yarn. This package simplifies the setup for using Jest with Puppeteer. ```bash yarn add --dev jest-puppeteer ``` -------------------------------- ### jest.useRealTimers() Source: https://jestjs.io/docs/30.0/jest-object Installs real timers. ```APIDOC ## jest.useRealTimers() ### Description Installs real timers, restoring the default behavior of `setTimeout`, `setInterval`, etc. ``` -------------------------------- ### Descriptive Snapshot Names Example Source: https://jestjs.io/docs/30.0/snapshot-testing Illustrates the use of descriptive names for snapshot tests to improve clarity during code reviews and debugging. The examples show how better names make it easier to identify incorrect snapshot outputs. ```javascript exports[` should handle some test case`] = `null`; exports[` should handle some other test case`] = `
Alan Turing
`; ``` ```javascript exports[` should render null`] = `null`; exports[` should render Alan Turing`] = `
Alan Turing
`; ``` ```javascript exports[` should render null`] = `
Alan Turing
`; exports[` should render Alan Turing`] = `null`; ``` -------------------------------- ### Install Jest Globals Type Definitions Source: https://jestjs.io/docs/30.0/getting-started Install the `@jest/globals` package to get type definitions for Jest's global APIs. This improves type checking in TypeScript test files. ```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 Jest with Yarn Source: https://jestjs.io/docs/30.0/getting-started Use this command to add Jest as a development dependency in your project using Yarn. ```bash yarn add --dev jest ``` -------------------------------- ### Global Setup Module for Jest Source: https://jestjs.io/docs/30.0/configuration Define a custom global setup module to run code once before all test suites. This module receives Jest's globalConfig and projectConfig and can set global variables for teardown. ```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; }; ``` -------------------------------- ### Basic transformIgnorePatterns Configuration (TypeScript) Source: https://jestjs.io/docs/30.0/configuration Configure `transformIgnorePatterns` to exclude specific directories from transformation. This example shows a common setup for TypeScript projects. ```typescript import type {Config} from 'jest'; const config: Config = { transformIgnorePatterns: ['/node_modules/(?!(foo|bar)/)', '/bar/'], }; export default config; ``` -------------------------------- ### Example Failure Output for `toBe` Source: https://jestjs.io/docs/30.0/expect Illustrates the formatted error message when a `toBe` assertion fails, showing the expected and received values clearly. ```text expect(received).toBe(expected) Expected value to be (using Object.is): "banana" Received: "apple" ``` -------------------------------- ### Timer Game Example Source: https://jestjs.io/docs/30.0/timer-mocks A simple timer game function that logs messages and calls a callback after a delay. ```javascript function timerGame(callback) { console.log('Ready....go!'); setTimeout(() => { console.log("Time's up -- stop!"); callback && callback(); }, 1000); } module.exports = timerGame; ``` -------------------------------- ### Jest Configuration with Custom Resolver (JavaScript) Source: https://jestjs.io/docs/30.0/configuration Example of configuring Jest to use a custom resolver defined in a local file. This is a common setup for projects requiring specific module resolution logic. ```javascript /** @type {import('jest').Config} */ const config = { resolver: '/resolver.js' }; module.exports = config; ``` -------------------------------- ### Example: `toBe` Matcher Implementation Source: https://jestjs.io/docs/30.0/expect Illustrates a practical implementation of a custom matcher (`toBe`) using the available `this` properties and utilities for clear error reporting. ```APIDOC ## Example: `toBe` Matcher Implementation This example shows how the built-in `toBe` matcher might be implemented using `expect.extend` and the available `this` context. ```javascript const {diff} = require('jest-diff'); expect.extend({ toBe(received, expected) { const options = { comment: 'Object.is equality', isNot: this.isNot, promise: this.promise, }; const pass = Object.is(received, expected); const message = pass ? () => this.utils.matcherHint('toBe', undefined, undefined, options) + '\n\n' + `Expected: not ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return ( this.utils.matcherHint('toBe', undefined, undefined, options) + '\n\n' + (diffString && diffString.includes('- Expect') ? `Difference:\n\n${diffString}` : `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(received)}`) ); }; return {actual: received, message, pass}; }, }); ``` ### Example Output When an assertion fails, the output might look like this: ``` expect(received).toBe(expected) Expected value to be (using Object.is): "banana" Received: "apple" ``` ``` -------------------------------- ### Jest Configuration for Custom Puppeteer Setup Source: https://jestjs.io/docs/30.0/puppeteer Configure Jest to use the custom global setup, global teardown, and test environment scripts. This setup allows for manual integration of Puppeteer with Jest. ```javascript module.exports = { globalSetup: './setup.js', globalTeardown: './teardown.js', testEnvironment: './puppeteer_environment.js', }; ``` -------------------------------- ### Implement `toBe` Matcher with Utilities Source: https://jestjs.io/docs/30.0/expect This example shows a full implementation of the `toBe` matcher, demonstrating the use of `this.isNot`, `this.promise`, `this.utils.matcherHint`, `this.utils.printExpected`, and `this.utils.printReceived` for detailed error messages. ```javascript const {diff} = require('jest-diff'); expect.extend({ toBe(received, expected) { const options = { comment: 'Object.is equality', isNot: this.isNot, promise: this.promise, }; const pass = Object.is(received, expected); const message = pass ? () => // eslint-disable-next-line prefer-template this.utils.matcherHint('toBe', undefined, undefined, options) + '\n\n' + `Expected: not ${this.utils.printExpected(expected)} ` + `Received: ${this.utils.printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return ( // eslint-disable-next-line prefer-template this.utils.matcherHint('toBe', undefined, undefined, options) + '\n\n' + (diffString && diffString.includes('- Expect') ? `Difference:\n\n${diffString}` : `Expected: ${this.utils.printExpected(expected)} ` + `Received: ${this.utils.printReceived(received)}`) ); }; return {actual: received, message, pass}; }, }); ``` -------------------------------- ### Replacing Mock Implementation with mockImplementation() Source: https://jestjs.io/docs/30.0/es6-class-mocks Shows how to replace the mock implementation of SoundPlayer using `mockImplementation()` within `beforeAll()` to simulate error conditions for testing. ```javascript import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); describe('When SoundPlayer throws an error', () => { beforeAll(() => { SoundPlayer.mockImplementation(() => { return { playSoundFile: () => { throw new Error('Test error'); }, }; }); }); it('Should throw an error when calling playSomethingCool', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); expect(() => soundPlayerConsumer.playSomethingCool()).toThrow(); }); }); ``` -------------------------------- ### Example Snapshot Artifact Source: https://jestjs.io/docs/30.0/snapshot-testing This is an example of a snapshot file generated by Jest. It represents the serializable output of a React component. ```javascript exports["renders correctly 1"] = " Facebook "; ``` -------------------------------- ### Using Fake Timers with Options Source: https://jestjs.io/docs/30.0/jest-object Demonstrates how to enable fake timers with specific configurations like automatic advancement or excluding certain APIs. ```javascript test('advance the timers automatically', () => { jest.useFakeTimers({advanceTimers: true}); // ... }); test('do not advance the timers and do not fake `performance`', () => { jest.useFakeTimers({doNotFake: ['performance']}); // ... }); test('uninstall fake timers for the rest of tests in the file', () => { jest.useRealTimers(); // ... }); ``` -------------------------------- ### Install jest-puppeteer with pnpm Source: https://jestjs.io/docs/30.0/puppeteer Install the jest-puppeteer package using pnpm. This package is essential for integrating Jest and Puppeteer testing. ```bash pnpm add --save-dev jest-puppeteer ``` -------------------------------- ### Create Jest configuration using npm, Yarn, or pnpm Source: https://jestjs.io/docs/30.0/upgrading-to-jest30 The `jest --init` command has been removed. Use package manager commands to scaffold a new Jest configuration file. ```bash npm init jest@latest ``` ```bash # Or for Yarn yarn create jest ``` ```bash # Or for pnpm pnpm create jest ``` -------------------------------- ### Configure Summary Reporter Options via Default Reporter Source: https://jestjs.io/docs/30.0/configuration Pass options to the summary reporter by configuring the default reporter. This example sets `summaryThreshold` to 10, which prints a detailed summary if the number of test suites exceeds this value. ```javascript /** @type {import('jest').Config} */ const config = { reporters: [['default', {summaryThreshold: 10}]], }; module.exports = config; ``` ```typescript import type {Config} from 'jest'; const config: Config = { reporters: [['default', {summaryThreshold: 10}]], }; export default config; ``` -------------------------------- ### Install Babel Dependencies with Yarn Source: https://jestjs.io/docs/30.0/getting-started Install the necessary Babel dependencies for Jest using Yarn. This includes babel-jest, @babel/core, and @babel/preset-env. ```bash yarn add --dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Importing a Manual Mock Before Tested File Source: https://jestjs.io/docs/30.0/manual-mocks When a manual mock needs to be applied before the tested file executes its code (e.g., when `window.matchMedia` is called directly in the tested file), import the mock file before importing the file under test. This ensures the mock is active when the tested code runs. ```javascript import './matchMedia.mock'; // Must be imported before the tested file import {myMethod} from './file-to-test'; describe('myMethod()', () => { // Test the method here... }); ``` -------------------------------- ### Run Jest from command line with options Source: https://jestjs.io/docs/30.0/getting-started Execute Jest tests matching a pattern, using a specific configuration file, and enabling native OS notifications upon completion. ```bash jest my-test --notify --config=config.json ``` -------------------------------- ### Install jest-environment-jsdom with Yarn Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the JSDOM test environment for Jest using Yarn. This package is required to simulate a browser DOM in your tests. ```bash yarn add --dev jest-environment-jsdom ``` -------------------------------- ### Install jest-environment-jsdom with npm Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the JSDOM test environment for Jest using npm. This package is required to simulate a browser DOM in your tests. ```bash npm install --save-dev jest-environment-jsdom ``` -------------------------------- ### Install jest-puppeteer with npm Source: https://jestjs.io/docs/30.0/puppeteer Install the jest-puppeteer package using npm. This package provides the necessary configuration for running Jest tests with Puppeteer. ```bash npm install --save-dev jest-puppeteer ``` -------------------------------- ### Enabling Legacy Fake Timers Source: https://jestjs.io/docs/30.0/jest-object Shows how to enable the legacy implementation of fake timers, which has limited configuration options. ```javascript jest.useFakeTimers({ legacyFakeTimers: true, }); ``` -------------------------------- ### Implement run Method for Watch Plugin Logic Source: https://jestjs.io/docs/30.0/watch-plugins Implement the `run` method to handle the logic when a user selects your plugin's key from the watch menu. This method can optionally trigger a test run using `updateConfigAndRun`. ```javascript class MyWatchPlugin { run(globalConfig, updateConfigAndRun) { // do something. } } ``` -------------------------------- ### Mocking Warning Module in Jest Setup Source: https://jestjs.io/docs/30.0/tutorial-react To suppress irrelevant warnings during testing, particularly with React Native, you can mock the `fbjs/lib/warning` module. This should be done in your Jest setup file and used cautiously. ```javascript jest.mock('fbjs/lib/warning', () => require('fbjs/lib/emptyFunction')); ``` -------------------------------- ### Generated Snapshot Output Source: https://jestjs.io/docs/30.0/tutorial-react-native This is an example of the snapshot file generated by Jest for the Intro component. It represents the component's rendered output and should be committed with code changes. ```javascript exports["Intro renders correctly 1"] = ` Welcome to React Native! This is a React Native snapshot test. `; ``` -------------------------------- ### Manual Mock Implementation for SoundPlayer Source: https://jestjs.io/docs/30.0/es6-class-mocks Defines a manual mock for the SoundPlayer class, exporting a mock function for `playSoundFile` and a mock implementation for the constructor. ```javascript // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { return {playSoundFile: mockPlaySoundFile}; }); export default mock; ``` -------------------------------- ### Configuring transformIgnorePatterns for pnpm (JavaScript) Source: https://jestjs.io/docs/30.0/configuration Configure `transformIgnorePatterns` to correctly handle packages managed by `pnpm`. This example demonstrates patterns for ignoring pnpm-specific symlinked directories. ```javascript /** @type {import('jest').Config} */ const config = { 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)', ], }; module.exports = config; ``` -------------------------------- ### jest.useFakeTimers(fakeTimersConfig?) Source: https://jestjs.io/docs/30.0/jest-object Installs fake timers. ```APIDOC ## jest.useFakeTimers(fakeTimersConfig?) ### Description Installs fake timers, allowing you to control time within your tests. You can provide a configuration object to customize the fake timer behavior. ### Parameters #### Path Parameters - **fakeTimersConfig** (object) - Optional - Configuration for fake timers. - **now** (number | Date) - Sets the initial time. - **timerConfig** (object) - Configuration for timers (e.g., `setTimeout`, `setInterval`). ``` -------------------------------- ### Example CommonJS Module Source: https://jestjs.io/docs/30.0/ecmascript-modules A basic CommonJS module structure that might be used in an Electron application. ```javascript const {BrowserWindow, app} = require('electron'); // etc. module.exports = {example}; ```