### Configure Setup Files After Environment Initialization Source: https://jestjs.io/docs/configuration Specify paths to modules that run code to configure the testing framework after it has been installed in the environment but before test code execution. ```javascript const {defineConfig} = require('jest'); module.exports = defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` ```typescript import {defineConfig} from 'jest'; export default defineConfig({ setupFilesAfterEnv: ['/setup-jest.js'], }); ``` -------------------------------- ### Writing Tests with Custom Puppeteer Setup Source: https://jestjs.io/docs/puppeteer Example test file demonstrating how to use the custom Puppeteer setup. It opens a new page, navigates to a URL, and performs an assertion using `page.evaluate`. ```javascript 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, ); ``` -------------------------------- ### Install @testing-library/react with Bun Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package using Bun for DOM testing. ```bash bun add --dev @testing-library/react ``` -------------------------------- ### Install Jest with Bun Source: https://jestjs.io/docs/30.0/getting-started Install Jest as a development dependency using Bun. ```bash bun add --dev jest ``` -------------------------------- ### Setup Database Before All Tests with beforeAll Source: https://jestjs.io/docs/30.0/api Use `beforeAll` to perform asynchronous setup once before any tests in the file execute. 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 @testing-library/react with npm Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package using npm for DOM testing. ```bash npm install --save-dev @testing-library/react ``` -------------------------------- ### Extend Jest Environment with Custom Setup Source: https://jestjs.io/docs/test-environment Define a custom Jest environment by extending a built-in one. This example shows how to set up a custom environment, typically used for specific testing needs. ```javascript module.exports = class MyEnvironment extends JestEnvironment { constructor(config, options) { super(config, options); } async setup() { await super.setup(); // Add custom setup logic here } async teardown() { // Add custom teardown logic here await super.teardown(); } }; ``` -------------------------------- ### Install Jest with pnpm Source: https://jestjs.io/docs/30.0/getting-started Install Jest as a development dependency using pnpm. ```bash pnpm add --save-dev jest ``` -------------------------------- ### Install @testing-library/react with pnpm Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package using pnpm for DOM testing. ```bash pnpm add --save-dev @testing-library/react ``` -------------------------------- ### Install @testing-library/react with Yarn Source: https://jestjs.io/docs/30.0/tutorial-react Install the @testing-library/react package using Yarn for DOM testing. ```bash yarn add --dev @testing-library/react ``` -------------------------------- ### Install identity-obj-proxy with Bun Source: https://jestjs.io/docs/webpack Install the `identity-obj-proxy` package using Bun. This command adds the package as a development dependency. ```bash bun add --dev identity-obj-proxy ``` -------------------------------- ### Install Jest Global Type Definitions Source: https://jestjs.io/docs/30.0/getting-started Install the `@jest/globals` package using npm, Yarn, pnpm, or Bun to get type definitions for Jest APIs. ```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 ``` -------------------------------- ### Webpack Configuration Example Source: https://jestjs.io/docs/webpack This is a common webpack configuration file that can be translated to a Jest setup. It defines rules for processing JavaScript, CSS, and various asset types. ```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 with npm Source: https://jestjs.io/docs/30.0/getting-started Install Jest as a development dependency using npm. ```bash npm install --save-dev jest ``` -------------------------------- ### 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 efficient for expensive operations that can be reused across all 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(); }); ``` -------------------------------- ### Asynchronous Repeating Setup with Promises Source: https://jestjs.io/docs/30.0/setup-teardown Handle asynchronous setup by returning a promise from `beforeEach`. This ensures that the test waits for the asynchronous operation to complete before running. ```javascript beforeEach(() => { return initializeCityDatabase(); }); ``` -------------------------------- ### Repeating Setup with beforeEach and afterEach Source: https://jestjs.io/docs/30.0/setup-teardown Use `beforeEach` and `afterEach` to run setup and teardown logic before and after each test in a file. This is useful for tasks that need to be repeated 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(); }); ``` -------------------------------- ### Custom Node.js Environment (TypeScript) Source: https://jestjs.io/docs/30.0/test-environment Extend NodeEnvironment in TypeScript for custom test environments. This example demonstrates setup, teardown, and accessing docblock pragmas. ```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') { // ... } } } ``` -------------------------------- ### Complete ES6 Class Mock Example Source: https://jestjs.io/docs/es6-class-mocks A full test file demonstrating mocking an ES6 class using the module factory parameter with `jest.mock`. Includes 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 Jest with Yarn Source: https://jestjs.io/docs/30.0/getting-started Install Jest as a development dependency using Yarn. ```bash yarn add --dev jest ``` -------------------------------- ### Install jest-puppeteer with Bun Source: https://jestjs.io/docs/30.0/puppeteer Install the `jest-puppeteer` package as a development dependency using Bun. ```bash bun add --dev jest-puppeteer ``` -------------------------------- ### Complete ES6 Class Mock Example Source: https://jestjs.io/docs/30.0/es6-class-mocks This complete test file demonstrates mocking a class using the module factory parameter with `jest.mock()`, 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 Jest and React Testing Dependencies (Bun) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest, babel-jest, and necessary Babel presets for React testing using Bun. ```bash bun add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Example CJS Module Source: https://jestjs.io/docs/30.0/ecmascript-modules This is an example of a CommonJS module that might be tested. ```javascript const {BrowserWindow, app} = require('electron'); // etc. module.exports = {example}; ``` -------------------------------- ### 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. ```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-mongodb Preset Source: https://jestjs.io/docs/30.0/mongodb Install the jest-mongodb preset using your preferred package manager. ```bash npm install --save-dev @shelf/jest-mongodb ``` ```bash yarn add --dev @shelf/jest-mongodb ``` ```bash pnpm add --save-dev @shelf/jest-mongodb ``` ```bash bun add --dev @shelf/jest-mongodb ``` -------------------------------- ### Install node-notifier for native notifications Source: https://jestjs.io/docs/configuration Install the `node-notifier` package to enable native OS notifications for test results. ```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 and React Testing Dependencies (npm) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest, babel-jest, and necessary Babel presets for React testing using npm. ```bash npm install --save-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 necessary Babel dependencies for Jest using Bun. ```bash bun add --dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Install identity-obj-proxy with pnpm Source: https://jestjs.io/docs/webpack Install the `identity-obj-proxy` package using pnpm. This command adds the package as a development dependency. ```bash pnpm add --save-dev identity-obj-proxy ``` -------------------------------- ### Install jest-dynamodb Preset Source: https://jestjs.io/docs/30.0/dynamodb Install the jest-dynamodb preset as a development dependency using npm, Yarn, pnpm, or Bun. ```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 ``` -------------------------------- ### 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 Jest and React Testing Dependencies (pnpm) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest, babel-jest, and necessary Babel presets for React testing using pnpm. ```bash pnpm add --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Example createUser function Source: https://jestjs.io/docs/bypassing-module-mocks This is the function under test that uses `node-fetch`. ```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; }; ``` -------------------------------- ### Utility Module Example Source: https://jestjs.io/docs/jest-object A simple utility module with an authorize function that returns a token. ```javascript export default { authorize: () => { return 'token'; }, }; ``` -------------------------------- ### Install identity-obj-proxy with Yarn Source: https://jestjs.io/docs/webpack Install the `identity-obj-proxy` package using Yarn. This is an alternative to npm for managing development dependencies. ```bash yarn add --dev identity-obj-proxy ``` -------------------------------- ### Jest Setup and Teardown Hooks Order Source: https://jestjs.io/docs/30.0/setup-teardown Demonstrates the execution order of multiple beforeEach and afterEach hooks, including nested describe blocks. This helps in understanding how Jest manages setup and teardown for dependent resources. ```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-puppeteer with pnpm Source: https://jestjs.io/docs/30.0/puppeteer Install the `jest-puppeteer` package as a development dependency using pnpm. ```bash pnpm add --save-dev jest-puppeteer ``` -------------------------------- ### Install Jest and React Testing Dependencies (Yarn) Source: https://jestjs.io/docs/30.0/tutorial-react Installs Jest, babel-jest, and necessary Babel presets for React testing using Yarn. ```bash yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer ``` -------------------------------- ### Install jest-puppeteer with npm Source: https://jestjs.io/docs/30.0/puppeteer Install the `jest-puppeteer` package as a development dependency using npm. ```bash npm install --save-dev jest-puppeteer ``` -------------------------------- ### JavaScript Resolver Example Source: https://jestjs.io/docs/30.0/configuration Example of a custom resolver using 'browser-resolve'. This module exports a synchronous resolver function. ```javascript const browserResolve = require('browser-resolve'); module.exports = browserResolve.sync; ``` -------------------------------- ### Install Babel dependencies with npm Source: https://jestjs.io/docs/30.0/getting-started Install necessary Babel dependencies for Jest using npm. ```bash npm install --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Example forEach Implementation Source: https://jestjs.io/docs/30.0/mock-functions This is the implementation of the forEach function that will be tested using mock functions. ```javascript export function forEach(items, callback) { for (const item of items) { callback(item); } } ``` -------------------------------- ### Install ts-jest for TypeScript Preprocessing Source: https://jestjs.io/docs/30.0/getting-started Install the ts-jest package using npm, Yarn, pnpm, or Bun to enable Jest to transpile TypeScript. ```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 Jest JSDOM Environment (Bun) Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the jest-environment-jsdom package using Bun to simulate a browser DOM environment for your tests. ```bash bun add --dev jest-environment-jsdom ``` -------------------------------- ### 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 ``` -------------------------------- ### Custom Global Setup Module Source: https://jestjs.io/docs/configuration Implement a custom setup module to run code once before all test suites. This function receives Jest's global and project configurations and can define 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; }; ``` -------------------------------- ### Global Setup Script for Jest Source: https://jestjs.io/docs/30.0/configuration Configure a custom global setup module using `globalSetup`. This script runs once before all test suites and can access Jest's global and project configurations. Globals defined here are only accessible in `globalTeardown`. ```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 @types/jest Package Source: https://jestjs.io/docs/30.0/getting-started Install the `@types/jest` package using npm, Yarn, pnpm, or Bun for Jest global type definitions. Match versions closely with Jest for best compatibility. ```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 ``` -------------------------------- ### Example sum.test.js file Source: https://jestjs.io/docs/30.0/getting-started A basic Jest test for the sum function. ```javascript const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); }); ``` -------------------------------- ### Setup and Teardown with Before/After Hooks Source: https://jestjs.io/docs/setup-teardown Demonstrates the execution order of `beforeEach` and `afterEach` hooks, including nested describe blocks. Note that `after*` hooks of enclosing scopes are called first. ```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 ``` -------------------------------- ### Example sum.js file Source: https://jestjs.io/docs/30.0/getting-started A simple JavaScript function that adds two numbers. ```javascript function sum(a, b) { return a + b; } module.exports = sum; ``` -------------------------------- ### Get Mock Implementation - TypeScript Source: https://jestjs.io/docs/mock-function-api Retrieves the current implementation of a mock function set via mockImplementation(). Returns undefined if no implementation has been set. Ensure Jest APIs are explicitly imported for TypeScript examples. ```typescript import {jest} from '@jest/globals'; const mockFn = jest.fn<() => number>(); mockFn.getMockImplementation(); // undefined mockFn.mockImplementation(() => 42); mockFn.getMockImplementation(); // () => 42 ``` -------------------------------- ### Creating a Jest Configuration File Source: https://jestjs.io/docs/30.0/upgrading-to-jest30 The interactive `jest --init` command has been removed. Use `npm init jest@latest`, `yarn create jest`, or `pnpm create jest` to scaffold a new Jest configuration file. ```bash npm init jest@latest ``` ```bash yarn create jest ``` ```bash pnpm create jest ``` -------------------------------- ### Jest Configuration with Multiple Transformers Source: https://jestjs.io/docs/webpack Example of configuring Jest's `transform` option to include multiple transformers. This setup explicitly includes the default `babel-jest` transformer alongside a custom transformer for CSS files, allowing for preprocessors. ```javascript "transform": { "\.[jt]sx?$": "babel-jest", "\.css$": "some-css-transformer", } ``` -------------------------------- ### 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', ], }, }; ``` -------------------------------- ### Configure Jest setup files Source: https://jestjs.io/docs/30.0/configuration Use `setupFilesAfterEnv` to specify modules that run code to configure or set up the testing framework before each test file. Jest globals like `jest` and `expect` are available in these modules. ```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; ``` -------------------------------- ### Global Setup Script for Puppeteer Source: https://jestjs.io/docs/30.0/puppeteer Launches a Puppeteer browser instance and exposes its WebSocket endpoint for test environments. Requires 'fs.promises', 'os', 'path', and 'puppeteer'. ```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()); }; ``` -------------------------------- ### Install jest-puppeteer with Yarn Source: https://jestjs.io/docs/30.0/puppeteer Install the `jest-puppeteer` package as a development dependency using Yarn. ```bash yarn add --dev jest-puppeteer ``` -------------------------------- ### Testing with async/await Source: https://jestjs.io/docs/tutorial-async Demonstrates testing asynchronous functions using the `async/await` syntax. This provides a more synchronous-looking way to write asynchronous tests. ```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'); }); ``` -------------------------------- ### Define Watch Menu Prompt with `getUsageInfo` Source: https://jestjs.io/docs/30.0/watch-plugins Shows how to add a custom command to the watch mode menu by implementing the `getUsageInfo` method, returning a key and a prompt string. ```javascript class MyWatchPlugin { getUsageInfo(globalConfig) { return { key: 's', prompt: 'do something', }; } } ``` -------------------------------- ### Install Babel dependencies with pnpm Source: https://jestjs.io/docs/30.0/getting-started Install necessary Babel dependencies for Jest using pnpm. ```bash pnpm add --save-dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Install Babel dependencies with Yarn Source: https://jestjs.io/docs/30.0/getting-started Install necessary Babel dependencies for Jest using Yarn. ```bash yarn add --dev babel-jest @babel/core @babel/preset-env ``` -------------------------------- ### Create a custom manual mock Source: https://jestjs.io/docs/30.0/tutorial-react-native Create your own manual mock for a native module, potentially modeling it after the real module's source code. ```javascript jest.mock('Text', () => { const RealComponent = require('jest-require-actual')('Text'); const React = require('react'); class Text extends React.Component { render() { return React.createElement('Text', this.props, this.props.children); } } Text.propTypes = RealComponent.propTypes; return Text; }); ``` -------------------------------- ### afterAll Example for Global Cleanup Source: https://jestjs.io/docs/30.0/api Use afterAll to run cleanup code after all tests in a file have completed. This is useful for releasing global resources. ```javascript const globalDatabase = makeGlobalDatabase(); function cleanUpDatabase(db) { db.cleanUp(); } afterAll(() => { cleanUpDatabase(globalDatabase); }); test('can find things', () => { return globalDatabase.find('thing', {}, results => { expect(results.length).toBeGreaterThan(0); }); }); test('can insert a thing', () => { return globalDatabase.insert('thing', makeThing(), response => { expect(response.success).toBeTruthy(); }); }); ``` -------------------------------- ### Install identity-obj-proxy for CSS Modules Source: https://jestjs.io/docs/webpack Install the `identity-obj-proxy` package as a development dependency. This package is used to mock CSS Modules in Jest. ```bash npm install --save-dev identity-obj-proxy ``` -------------------------------- ### Install Jest JSDOM Environment (pnpm) Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the jest-environment-jsdom package using pnpm to simulate a browser DOM environment for your tests. ```bash pnpm add --save-dev jest-environment-jsdom ``` -------------------------------- ### Global Setup Script for Puppeteer Source: https://jestjs.io/docs/puppeteer This script launches Puppeteer and exposes its WebSocket endpoint for test environments. It creates a temporary directory to store the endpoint. ```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()); }; ``` -------------------------------- ### Install Jest JSDOM Environment (Yarn) Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the jest-environment-jsdom package using Yarn to simulate a browser DOM environment for your tests. ```bash yarn add --dev jest-environment-jsdom ``` -------------------------------- ### Install Jest JSDOM Environment (npm) Source: https://jestjs.io/docs/30.0/tutorial-jquery Install the jest-environment-jsdom package using npm to simulate a browser DOM environment for your tests. ```bash npm install --save-dev jest-environment-jsdom ``` -------------------------------- ### Implement 'toBe' Matcher with Helper Utilities Source: https://jestjs.io/docs/30.0/expect Demonstrates the implementation of the built-in `toBe` matcher, showcasing the use of `this.isNot`, `this.promise`, `this.utils.matcherHint`, `this.utils.printExpected`, and `this.utils.printReceived` for constructing informative 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}; }, }); ``` -------------------------------- ### Asynchronous Test Definition Example (Not Recommended) Source: https://jestjs.io/docs/troubleshooting Tests must be defined synchronously for Jest to collect them. This example shows an asynchronous definition that will not work. ```javascript // Don't do this it will not work setTimeout(() => { it('passes', () => expect(1).toBe(1)); }, 0); ``` -------------------------------- ### Jest Transform Configuration Example Source: https://jestjs.io/docs/30.0/webpack Example of configuring Jest's 'transform' option to include multiple transformers, such as babel-jest and a CSS transformer. ```json "transform": { "\.[jt]sx?$": "babel-jest", "\.css$": "some-css-transformer" } ``` -------------------------------- ### Install jest-environment-jsdom with Bun Source: https://jestjs.io/docs/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 ``` -------------------------------- ### Generate Jest config with Bun Source: https://jestjs.io/docs/30.0/getting-started Initialize Jest configuration using Bun. ```bash bunx create-jest ``` -------------------------------- ### Install jest-environment-jsdom with pnpm Source: https://jestjs.io/docs/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 ``` -------------------------------- ### Importing Manual Mock Before Tested File Source: https://jestjs.io/docs/30.0/manual-mocks When a method like window.matchMedia is called directly in the tested file, move the manual mock to a separate file and import it before the tested file. This ensures the mock is active when the code is executed. ```javascript import './matchMedia.mock'; // Must be imported before the tested file import {myMethod} from './file-to-test'; describe('myMethod()', () => { // Test the method here... }); ``` -------------------------------- ### Install jest-environment-jsdom with Yarn Source: https://jestjs.io/docs/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 ``` -------------------------------- ### Mocking Class Constructors with `mockImplementation()` Source: https://jestjs.io/docs/30.0/mock-function-api Demonstrates how to use `mockImplementation` to mock a class constructor, returning an object with a mocked method. This is useful for testing interactions with class instances. ```javascript module.exports = class SomeClass { method(a, b) {} }; ``` ```javascript const SomeClass = require('./SomeClass'); jest.mock('./SomeClass'); // this happens automatically with automocking const mockMethod = jest.fn(); SomeClass.mockImplementation(() => { return { method: mockMethod, }; }); const some = new SomeClass(); some.method('a', 'b'); console.log('Calls to method:', mockMethod.mock.calls); ``` ```typescript export class SomeClass { method(a: string, b: string): void {} } ``` ```typescript import {jest} from '@jest/globals'; import {SomeClass} from './SomeClass'; jest.mock('./SomeClass'); // this happens automatically with automocking const mockMethod = jest.fn<(a: string, b: string) => void>(); jest.mocked(SomeClass).mockImplementation(() => { return { method: mockMethod, }; }); const some = new SomeClass(); some.method('a', 'b'); console.log('Calls to method:', mockMethod.mock.calls); ```