### Vitest Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Setup for Vitest projects. Configure Vitest to use a setup file that imports the Vitest-specific matchers. ```typescript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { setupFiles: ['./vitest.setup.ts'], environment: 'jsdom' } }) ``` ```typescript import '@testing-library/jest-dom/vitest' ``` ```typescript import { expect, test } from 'vitest' test('element is visible', () => { expect(element).toBeVisible() }) ``` -------------------------------- ### Monorepo Jest Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Configure Jest for a monorepo structure. This example defines multiple Jest projects and a root setup file for shared configurations. ```javascript module.exports = { projects: [ '/packages/*/jest.config.js' ], setupFilesAfterEnv: ['/jest.setup.js'] } ``` ```javascript import '@testing-library/jest-dom' ``` -------------------------------- ### Default Jest Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Recommended setup for Jest. Import the matchers in your Jest setup file and configure Jest to use it. ```javascript import '@testing-library/jest-dom' ``` ```javascript module.exports = { setupFilesAfterEnv: ['/jest.setup.js'] } ``` ```javascript test('element is visible', () => { expect(element).toBeVisible() }) ``` -------------------------------- ### Run Setup Verification Test Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Execute this command in your terminal to run the setup verification test. A passing result indicates that jest-dom is correctly installed and configured. ```bash npm test -- test/setup.test.js ``` -------------------------------- ### Minimal Jest Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Configure Jest with a minimal setup for testing. This includes setting the test environment to 'jsdom' and specifying the setup file. ```javascript module.exports = { testEnvironment: 'jsdom', setupFilesAfterEnv: ['/jest.setup.js'] } ``` ```javascript import '@testing-library/jest-dom' ``` -------------------------------- ### TypeScript Setup Source: https://github.com/testing-library/jest-dom/blob/main/README.md Guidance on configuring TypeScript for @testing-library/jest-dom, including setup file extensions and tsconfig.json inclusion. ```APIDOC ### With TypeScript If you're using TypeScript, make sure your setup file is a `.ts` and not a `.js` to include the necessary types. You will also need to include your setup file in your `tsconfig.json` if you haven't already: ```json // In tsconfig.json "include": [ ... "./jest-setup.ts" ], ``` ``` -------------------------------- ### Complete Vitest Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Configure Vitest with React support, jsdom environment, and global setup files. This setup is suitable for modern React projects using Vitest. ```typescript import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], test: { globals: true, environment: 'jsdom', setupFiles: ['./vitest.setup.ts'] } }) ``` ```typescript import '@testing-library/jest-dom/vitest' ``` -------------------------------- ### Vitest Setup Source: https://github.com/testing-library/jest-dom/blob/main/README.md Instructions for integrating @testing-library/jest-dom with Vitest, including setup file configuration and TypeScript types. ```APIDOC ## With Vitest If you are using [vitest][], this module will work as-is, but you will need to use a different import in your tests setup file. This file should be added to the [`setupFiles`][vitest setupfiles] property in your vitest config: ```javascript // In your own vitest-setup.js (or any other name) import '@testing-library/jest-dom/vitest' // In vitest.config.js add (if you haven't already) setupFiles: ['./vitest-setup.js'] ``` Also, depending on your local setup, you may need to update your `tsconfig.json`: ```json // In tsconfig.json "compilerOptions": { ... "types": ["vitest/globals", "@testing-library/jest-dom"] }, "include": [ ... "./vitest-setup.ts" ], ``` [vitest]: https://vitest.dev/ [vitest setupfiles]: https://vitest.dev/config/#setupfiles ``` -------------------------------- ### Correct Jest Setup Files Configuration Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Use 'setupFilesAfterEnv' in jest.config.js to specify your setup file. ```javascript // Correct module.exports = { setupFilesAfterEnv: ['/jest.setup.js'] } ``` -------------------------------- ### Basic Jest Setup for jest-dom Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/README.md Configure Jest to use jest-dom by importing the library in your setup file and configuring Jest's environment and setup files. ```javascript // jest.setup.js import '@testing-library/jest-dom' // jest.config.js module.exports = { testEnvironment: 'jsdom', setupFilesAfterEnv: ['/jest.setup.js'] } ``` -------------------------------- ### Install jest-dom with npm Source: https://github.com/testing-library/jest-dom/blob/main/README.md Install jest-dom as a development dependency using npm. ```bash npm install --save-dev @testing-library/jest-dom ``` -------------------------------- ### Install jest-dom with yarn Source: https://github.com/testing-library/jest-dom/blob/main/README.md Install jest-dom as a development dependency using yarn. ```bash yarn add --dev @testing-library/jest-dom ``` -------------------------------- ### Complete Jest + React Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md A comprehensive Jest configuration for React projects. It includes preset, test environment, setup files, module name mapping, and transform ignore patterns. ```javascript module.exports = { preset: 'react-native', testEnvironment: 'jsdom', setupFilesAfterEnv: ['/jest.setup.js'], moduleNameMapper: { '\.(css|less|scss|sass)$': 'identity-obj-proxy' }, transformIgnorePatterns: [ 'node_modules/(?!(react-native)/)' ] } ``` ```javascript import '@testing-library/jest-dom' ``` -------------------------------- ### Jest-compatible Expect Setup Source: https://github.com/testing-library/jest-dom/blob/main/README.md Instructions for using @testing-library/jest-dom with other Jest-compatible `expect` interfaces. ```APIDOC ### With another Jest-compatible `expect` If you are using a different test runner that is compatible with Jest's `expect` interface, it might be possible to use it with this library: ```javascript import * as matchers from '@testing-library/jest-dom/matchers' import {expect} from 'my-test-runner/expect' expect.extend(matchers) ``` ``` -------------------------------- ### Setup Jest DOM with Vitest Source: https://github.com/testing-library/jest-dom/blob/main/README.md Import '@testing-library/jest-dom/vitest' for Vitest. Ensure your vitest config includes the setup file in 'setupFiles'. ```javascript // In your own vitest-setup.js (or any other name) import '@testing-library/jest-dom/vitest' ``` ```javascript // In vitest.config.js add (if you haven't already) setupFiles: ['./vitest-setup.js'] ``` -------------------------------- ### Install Jest DOM Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Install @testing-library/jest-dom as a development dependency using npm. ```bash npm install --save-dev @testing-library/jest-dom ``` -------------------------------- ### Ensure Setup File is Loaded in Jest Config Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Specify the setup file in 'setupFilesAfterEnv' within jest.config.js to ensure it's loaded. ```javascript // jest.config.js module.exports = { testEnvironment: 'jsdom', setupFilesAfterEnv: ['/jest.setup.js'] // Must be specified } ``` -------------------------------- ### Jest Setup with @jest/globals Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Alternative Jest setup using @jest/globals for type safety and explicit global usage. Ensure jsdom environment is configured. ```javascript import '@testing-library/jest-dom/jest-globals' ``` ```javascript module.exports = { testEnvironment: 'jsdom', setupFilesAfterEnv: ['/jest.setup.js'] } ``` -------------------------------- ### Setup jest-dom in Jest Source: https://github.com/testing-library/jest-dom/blob/main/README.md Import jest-dom in your Jest setup file and configure Jest to use it. ```javascript // In your own jest-setup.js (or any other name) import '@testing-library/jest-dom' // In jest.config.js add (if you haven't already) setupFilesAfterEnv: ['/jest-setup.js'] ``` -------------------------------- ### Install @testing-library/jest-dom Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Install the package as a development dependency using npm, yarn, or pnpm. ```bash npm install --save-dev @testing-library/jest-dom # or yarn add --dev @testing-library/jest-dom # or pnpm add -D @testing-library/jest-dom ``` -------------------------------- ### TypeScript Configuration for Jest Setup Source: https://github.com/testing-library/jest-dom/blob/main/README.md Ensure your TypeScript setup file is included in tsconfig.json. ```json // In tsconfig.json "include": [ ... "./jest-setup.ts" ], ``` -------------------------------- ### Import Jest DOM Matchers in Setup File Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Import '@testing-library/jest-dom' at the top level of your setup file (e.g., jest.setup.js) to make matchers available. ```javascript // jest.setup.js import '@testing-library/jest-dom' // Must be at top level // NOT in test files (unless using standalone import) // NOT in jest.config.js ``` -------------------------------- ### Jest Setup with @jest/globals Source: https://github.com/testing-library/jest-dom/blob/main/README.md Instructions for setting up @testing-library/jest-dom when using `@jest/globals` with `injectGlobals: false`. ```APIDOC ## Setup with `@jest/globals` If you are using [`@jest/globals`][jest-globals announcement] with [`injectGlobals: false`][inject-globals docs], you will need to use a different import in your tests setup file: ```javascript // In your own jest-setup.js (or any other name) import '@testing-library/jest-dom/jest-globals' ``` [jest-globals announcement]: https://jestjs.io/blog/2020/05/05/jest-26#a-new-way-to-consume-jest---jestglobals [inject-globals docs]: https://jestjs.io/docs/configuration#injectglobals-boolean ``` -------------------------------- ### Jest Setup with TypeScript Declarations Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Import @testing-library/jest-dom in your Jest setup file and declare global matchers for TypeScript. ```typescript import '@testing-library/jest-dom' declare global { namespace jest { interface Matchers { toBeInTheDocument(): R toBeVisible(): R toBeDisabled(): R // ... other matchers } } } ``` -------------------------------- ### TypeScript Configuration for Vitest Setup Source: https://github.com/testing-library/jest-dom/blob/main/README.md Update tsconfig.json to include Vitest globals and jest-dom types, and include the setup file. ```json // In tsconfig.json "compilerOptions": { ... "types": ["vitest/globals", "@testing-library/jest-dom"] }, "include": [ ... "./vitest-setup.ts" ], ``` -------------------------------- ### Bun Runtime Support Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Configure Bun test runner and preload the @testing-library/jest-dom setup file for runtime support. ```toml [test] root = "src" ``` ```typescript import '@testing-library/jest-dom' ``` ```bash bun test --preload ./test.setup.ts ``` -------------------------------- ### toHaveValue() - Example Test Case Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md A practical example demonstrating how to use `toHaveValue()` within a test case to verify the values of email, number, and select form inputs. ```javascript test('form inputs have expected values', () => { const emailInput = document.querySelector('[type="email"]') emailInput.value = 'user@example.com' expect(emailInput).toHaveValue('user@example.com') const ageInput = document.querySelector('[type="number"]') ageInput.value = '25' expect(ageInput).toHaveValue(25) const select = document.querySelector('select') expect(select).toHaveValue('option1') }) ``` -------------------------------- ### Examples for toBeVisible matcher Source: https://github.com/testing-library/jest-dom/blob/main/README.md Demonstrates various scenarios for the `toBeVisible` matcher, including elements hidden by CSS properties, attributes, or parent visibility. ```html
Zero Opacity Example
Visibility Hidden Example
Display None Example
Hidden Parent Example
Visible Example
Title of hidden text Hidden Details Example
Title of visible text
Visible Details Example
``` ```javascript expect(getByText('Zero Opacity Example')).not.toBeVisible() expect(getByText('Visibility Hidden Example')).not.toBeVisible() expect(getByText('Display None Example')).not.toBeVisible() expect(getByText('Hidden Parent Example')).not.toBeVisible() expect(getByText('Visible Example')).toBeVisible() expect(getByText('Hidden Attribute Example')).not.toBeVisible() expect(getByText('Hidden Details Example')).not.toBeVisible() expect(getByText('Visible Details Example')).toBeVisible() ``` -------------------------------- ### Incorrect Jest Setup Files Configuration Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md The 'setupTestFrameworkScriptFile' property is an old API and should not be used. ```javascript // Wrong module.exports = { setupTestFrameworkScriptFile: ['/jest.setup.js'] // Old API } ``` -------------------------------- ### Bun Test Setup for jest-dom Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/README.md Configure Bun's test runner to use jest-dom by specifying a preload script. ```bash bun test --preload ./test.setup.ts ``` -------------------------------- ### Setup Jest DOM with @jest/globals Source: https://github.com/testing-library/jest-dom/blob/main/README.md Import '@testing-library/jest-dom/jest-globals' when using '@jest/globals' with 'injectGlobals: false'. ```javascript // In your own jest-setup.js (or any other name) import '@testing-library/jest-dom/jest-globals' ``` -------------------------------- ### NodeTypeError Examples Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/errors-and-exceptions.md Shows examples that trigger a NodeTypeError, which occurs when a matcher expects a valid DOM Node but receives an invalid argument. ```javascript expect(null).toHaveTextContent('text') // throws NodeTypeError expect('string').toHaveTextContent('x') // throws NodeTypeError ``` -------------------------------- ### Complex Form Example with toHaveFormValues() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md This example demonstrates `toHaveFormValues` with a complex form, including multiple checkboxes with the same name, radio buttons, and a multi-select dropdown. It shows how to handle array values for checkboxes and multi-selects. ```javascript test('complex form has expected values', () => { const form = document.querySelector('form') // Multiple checkboxes with same name const checkboxes = form.querySelectorAll('[name="interests"]') checkboxes[0].checked = true // JavaScript checkboxes[2].checked = true // Python // Radio buttons const maleRadio = form.querySelector('[value="male"]') maleRadio.checked = true // Select multiple const skillsSelect = form.querySelector('[name="skills"]') skillsSelect.options[0].selected = true // React skillsSelect.options[2].selected = true // Vue expect(form).toHaveFormValues({ username: 'john', interests: ['JavaScript', 'Python'], gender: 'male', skills: ['react', 'vue'] }) }) ``` -------------------------------- ### Test disabled elements with toBeDisabled Source: https://github.com/testing-library/jest-dom/blob/main/README.md Examples demonstrating the use of the toBeDisabled matcher on buttons, inputs within fieldsets, and links. ```javascript expect(getByTestId('button')).toBeDisabled() expect(getByTestId('input')).toBeDisabled() expect(getByText('link')).not.toBeDisabled() ``` -------------------------------- ### HtmlElementTypeError Examples Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/errors-and-exceptions.md Illustrates scenarios where HtmlElementTypeError is thrown, typically when a matcher receives an argument that is not a valid HTMLElement or SVGElement. ```javascript expect(document).toBeDisabled() // throws HtmlElementTypeError expect(null).toBeVisible() // throws HtmlElementTypeError expect('string').toHaveAttribute('id') // throws HtmlElementTypeError ``` -------------------------------- ### Standalone Matchers Setup Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Manually extend Jest's expect with matchers for custom test runner integrations. This method requires explicit extension. ```javascript import { expect } from '@jest/globals' import matchers from '@testing-library/jest-dom/matchers' expect.extend(matchers) ``` ```javascript // Matchers are now available on expect expect(element).toBeInTheDocument() ``` -------------------------------- ### Test empty DOM elements with toBeEmptyDOMElement Source: https://github.com/testing-library/jest-dom/blob/main/README.md Examples showing how to use toBeEmptyDOMElement to check for empty spans, and asserting that non-empty or whitespace-containing spans are not empty. ```javascript expect(getByTestId('empty')).toBeEmptyDOMElement() expect(getByTestId('not-empty')).not.toBeEmptyDOMElement() expect(getByTestId('with-whitespace')).not.toBeEmptyDOMElement() ``` -------------------------------- ### InvalidCSSError Example Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/errors-and-exceptions.md Demonstrates how an InvalidCSSError is thrown when the CSS string provided to the `toHaveStyle` matcher contains syntax errors. ```javascript const div = document.querySelector('div') expect(div).toHaveStyle('invalid css syntax }{') // throws: InvalidCSSError - Syntax error parsing expected css: ... ``` -------------------------------- ### Value Handling Examples for toHaveFormValues() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md Illustrates how `toHaveFormValues` handles different form field types, including single inputs, multiple checkboxes, radio buttons, and multi-select elements. Note the array format for multiple selections. ```javascript // Single input expectedValues: { username: 'john' } // Multiple values (checkboxes with same name) expectedValues: { tags: ['javascript', 'testing'] // array of checked values } // Radio button (only one can be selected) expectedValues: { gender: 'male' // single value from checked radio } // Select multiple expectedValues: { colors: ['red', 'blue'] // array of selected values } ``` -------------------------------- ### Matchers Standalone Export Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Import the matchers directly for manual integration with `expect.extend`. This provides raw matcher objects and is useful for custom setups or when you don't want to extend the global `expect` object. ```javascript import matchers from '@testing-library/jest-dom/matchers' expect.extend(matchers) ``` -------------------------------- ### Vitest Export Import Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Import the Vitest export to use matchers specifically configured for the Vitest testing framework. Ensure you have Vitest installed and configured in your project. ```javascript import '@testing-library/jest-dom/vitest' ``` -------------------------------- ### Import Jest DOM Matchers Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/api-reference-dom-matchers.md Import the jest-dom matchers into your test environment. Choose the appropriate import based on your setup (e.g., standard Jest or Vitest). ```javascript import '@testing-library/jest-dom' // or import '@testing-library/jest-dom/jest-globals' // or with Vitest import '@testing-library/jest-dom/vitest' ``` -------------------------------- ### Configure Jest Environment for jsdom Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/README.md Configure your Jest environment to use jsdom for DOM testing. This is a required setup for jest-dom. ```javascript module.exports = { testEnvironment: 'jsdom' } ``` ```javascript module.exports = { testEnvironment: 'node' } ``` -------------------------------- ### toHaveValue() - Value Type Coercion Examples Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md Demonstrates how `toHaveValue()` handles type coercion for number inputs and checks for empty values. It also shows usage with text inputs and multiple select elements. ```javascript const numberInput = document.querySelector('input[type="number"]') numberInput.value = '5' expect(numberInput).toHaveValue(5) // Coerced to number expect(numberInput).not.toHaveValue('5') // String doesn't match // Empty number input numberInput.value = '' expect(numberInput).toHaveValue(null) // Empty becomes null // Text input const textInput = document.querySelector('input[type="text"]') textInput.value = 'John' expect(textInput).toHaveValue('John') // Multiple select const select = document.querySelector('select[multiple]') expect(select).toHaveValue(['option1', 'option2']) ``` -------------------------------- ### Verify jest-dom Matchers Availability Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md This test verifies that jest-dom matchers are available and working correctly. It creates a simple DOM element and asserts its presence and visibility using jest-dom matchers. Ensure this test passes to confirm proper setup. ```javascript test('jest-dom matchers are available', () => { const element = document.createElement('div') document.body.appendChild(element) // All these should work without errors expect(element).toBeInTheDocument() expect(element).toBeVisible() expect(element).not.toBeDisabled() }) ``` -------------------------------- ### Main jest-dom Entry Point Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/README.md Import the main entry point to extend Jest's expect with all jest-dom matchers. ```javascript import '@testing-library/jest-dom' expect.extend(/* matchers automatically extended */) ``` -------------------------------- ### getInputValue() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Gets the current value of an input element, performing type coercion for numbers and checkboxes. ```APIDOC ## getInputValue() ### Description Gets the current value of an input element, performing type coercion for numbers and checkboxes. ### Signature ```javascript function getInputValue(inputElement) ``` ### Parameters #### Path Parameters - **inputElement** (HTMLInputElement) - Input element to get value from ### Return any - The input's current value, with type coercion ### Behavior 1. For `type="number"`: - Returns null if value is empty string - Otherwise returns Number(value) 2. For `type="checkbox"`: - Returns the `.checked` boolean property 3. For other types: - Returns the string `.value` property ### Example ```javascript getInputValue(textInput) // Returns: "John" (string) getInputValue(numberInput) // Returns: 42 (number) getInputValue(emptyNumberInput) // Returns: null getInputValue(checkbox) // Returns: true or false ``` ``` -------------------------------- ### toSentence() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Formats an array of strings into a human-readable sentence, with customizable connectors for list items. ```APIDOC ## toSentence() ### Description Formats an array of strings into a human-readable sentence, with customizable connectors for list items. ### Signature ```javascript function toSentence(array, {wordConnector, lastWordConnector} = {}) ``` ### Parameters #### Path Parameters - **array** (string[]) - Required - Array of words to join - **wordConnector** (string) - Optional - Separator between non-final items (default: ', ') - **lastWordConnector** (string) - Optional - Separator before last item (default: ' and ') ### Return string - Sentence-formatted string ### Behavior 1. Joins all but last element with wordConnector 2. Joins result with last element using lastWordConnector 3. Returns single item as-is if array length is 1 ### Request Example ```javascript toSentence(['apple', 'orange', 'banana']) // Returns: "apple, orange and banana" toSentence(['a', 'b'], {lastWordConnector: ' or '}) // Returns: "a or b" toSentence(['single']) // Returns: "single" ``` ``` -------------------------------- ### getAccessibleValue() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Gets the accessible value of an element if its role supports it (e.g., meter, progressbar, slider, spinbutton). ```APIDOC ## getAccessibleValue() ### Description Gets the accessible value of an element if its role supports it (e.g., meter, progressbar, slider, spinbutton). ### Signature ```javascript function getAccessibleValue(element) ``` ### Parameters #### Path Parameters - **element** (HTMLElement) - Element to get accessible value from ### Return number or undefined ### Behavior 1. Checks element's `role` attribute 2. Only returns value if role is in supported list: meter, progressbar, slider, spinbutton 3. Returns Number value of `aria-valuenow` attribute if role matches 4. Returns undefined if role not supported ### Example ```javascript // Element with role="slider" and aria-valuenow="50" getAccessibleValue(slider) // Returns: 50 // Element with role="button" getAccessibleValue(button) // Returns: undefined ``` ``` -------------------------------- ### Incorrect Test Environment Configuration Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Using a 'node' test environment will result in errors as the DOM is not available. ```javascript module.exports = { testEnvironment: 'node' // Error: DOM not available } ``` -------------------------------- ### Configure Vitest Test Environment Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Configure Vitest to use the 'jsdom' environment for DOM testing. ```javascript export default defineConfig({ test: { environment: 'jsdom' } }) ``` -------------------------------- ### Get Element Tag Name Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Converts an element's tag name to lowercase. Returns undefined if the element has no tagName. ```javascript function getTag(element) // Returns: "button" getTag(document.querySelector('DIV')) // Returns: "div" ``` -------------------------------- ### Get Select Element Value Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Retrieves the value(s) from a select element. Returns a string for single selects and an array of strings for multi-selects. ```javascript // Single select with one selected option getSelectValue({multiple: false, options: [...]}) // Returns: "banana" // Multiple select with two selected options getSelectValue({multiple: true, options: [...]}) // Returns: ["apple", "orange"] ``` -------------------------------- ### Main Export Import Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Import the main export of @testing-library/jest-dom to extend the global expect with all matchers. This is the most common way to import the library. ```javascript import '@testing-library/jest-dom' ``` ```javascript const matchers = require('@testing-library/jest-dom') ``` -------------------------------- ### Get Accessible Element Value Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Retrieves the accessible value of an element if its role supports it (e.g., slider, progressbar). Returns the aria-valuenow attribute. ```javascript // Element with role="slider" and aria-valuenow="50" getAccessibleValue(slider) // Returns: 50 // Element with role="button" getAccessibleValue(button) // Returns: undefined ``` -------------------------------- ### toHaveAccessibleDescription Source: https://github.com/testing-library/jest-dom/blob/main/README.md Asserts that an element has an accessible description. It can check for the presence of a description or a specific description string/regex. ```APIDOC ## toHaveAccessibleDescription ### Description This allows you to assert that an element has the expected accessible description. It is useful for elements that have an `aria-describedby` attribute or a `title` attribute. ### Method Signature ```typescript toHaveAccessibleDescription(expectedAccessibleDescription?: string | RegExp) ``` ### Parameters * **expectedAccessibleDescription** (string | RegExp) - Optional. The expected accessible description or a RegExp to match against. ### Examples ```javascript // Assert an element has an accessible description expect(getByTestId('link')).toHaveAccessibleDescription() // Assert an element has a specific accessible description expect(getByTestId('link')).toHaveAccessibleDescription('A link to start over') // Assert an element does not have a specific accessible description expect(getByTestId('link')).not.toHaveAccessibleDescription('Home page') ``` ``` -------------------------------- ### Replace Deprecated Matcher Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/setup-and-import.md Use the recommended 'toBeEmptyDOMElement()' matcher instead of the deprecated 'toBeEmpty()'. ```javascript // Old - deprecated expect(element).toBeEmpty() // New - recommended expect(element).toBeEmptyDOMElement() ``` -------------------------------- ### Get Input Element Value Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Retrieves the value of an input element, performing type coercion. Handles numbers, checkboxes, and other input types differently. ```javascript getInputValue(textInput) // Returns: "John" (string) getInputValue(numberInput) // Returns: 42 (number) getInputValue(emptyNumberInput) // Returns: null getInputValue(checkbox) // Returns: true or false ``` -------------------------------- ### toHaveFormValues() Example Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md Use `toHaveFormValues` to check if a form element contains the expected values for multiple fields at once. Ensure the form element and its fields are correctly populated before the assertion. ```javascript test('form has expected values', () => { const form = document.querySelector('form') // Populate form form.elements.username.value = 'jane' form.elements.email.value = 'jane@example.com' form.elements.newsletter.checked = true // Check multiple field values at once expect(form).toHaveFormValues({ username: 'jane', email: 'jane@example.com', newsletter: true }) }) ``` -------------------------------- ### Get Single Form Element Value Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Retrieves the value of a form element. Delegates to specific handlers for inputs and selects, otherwise checks for a .value property or ARIA attribute. ```javascript getSingleElementValue(textInput) // Returns: "some text" getSingleElementValue(numberInput) // Returns: 5 (number) getSingleElementValue(select) // Returns: "option-value" getSingleElementValue(div) // Returns: undefined or ARIA value ``` -------------------------------- ### toBeEnabled() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md Asserts that an element is enabled. This is the inverse of `toBeDisabled()` and is recommended for clarity to avoid double negations. ```APIDOC ## toBeEnabled() ### Description Inverse of `toBeDisabled()`. Use this to avoid double negation. ### Method `toBeEnabled()` ### Parameters None ### Example ```javascript test('buttons are enabled', () => { const button = document.querySelector('button') expect(button).toBeEnabled() // Instead of: expect(button).not.toBeDisabled() }) ``` ``` -------------------------------- ### toHaveFormValues() Mixed Type Groups Error Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/errors-and-exceptions.md When using .toHaveFormValues(), ensure that all form elements sharing the same 'name' attribute are of the same 'type'. This example shows an invalid HTML structure that would trigger an error. ```html
``` -------------------------------- ### toBeEmpty Source: https://github.com/testing-library/jest-dom/blob/main/README.md Asserts whether an element has content or not. This matcher is deprecated and will be removed in the future. Use `toBeEmptyDOMElement` instead. ```APIDOC ## toBeEmpty ### Description Asserts whether an element has content or not. This matcher is deprecated. ### Method `expect(element).toBeEmpty()` ### Parameters #### Path Parameters - **element** (HTMLElement) - The element to check. ### Request Example ```javascript expect(getByTestId('empty')).toBeEmpty() expect(getByTestId('not-empty')).not.toBeEmpty() ``` ### Response #### Success Response (200) - **boolean** - True if the assertion passes, false otherwise. #### Response Example ```json { "example": "true" } ``` ``` -------------------------------- ### toHaveValue() - Usage Patterns Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/form-validation-matchers.md Illustrates common ways to use the `toHaveValue()` matcher for checking exact values, numeric values, array values in multiple selects, and the presence or absence of any value. ```javascript // Check exact value expect(input).toHaveValue('expected value') // Check numeric value expect(numberInput).toHaveValue(42) // Check array of values (multiple select) expect(multiSelect).toHaveValue(['red', 'blue']) // Check that element has some value (not empty) expect(input).toHaveValue() // Check that element doesn't have a value expect(input).not.toHaveValue() ``` -------------------------------- ### toAppearAfter Source: https://github.com/testing-library/jest-dom/blob/main/README.md Asserts that one element appears after another element in the DOM. This matcher does not take into account CSS styles that may modify the display order of elements. ```APIDOC ## toAppearAfter ### Description Asserts that one element appears after another element in the DOM. ### Method `expect(element).toAppearAfter(otherElement)` ### Parameters #### Path Parameters - **element** (HTMLElement) - The element to check. - **otherElement** (HTMLElement) - The element that should appear before the checked element. ### Request Example ```javascript const textA = queryByTestId('text-a') const textB = queryByTestId('text-b') expect(textB).toAppearAfter(textA) expect(textA).not.toAppearAfter(textB) ``` ### Response #### Success Response (200) - **boolean** - True if the assertion passes, false otherwise. #### Response Example ```json { "example": "true" } ``` ``` -------------------------------- ### Use toBeEmptyDOMElement matcher Source: https://github.com/testing-library/jest-dom/blob/main/README.md Assert that an element has no visible content for the user. This matcher ignores comments but fails on whitespace. ```typescript toBeEmptyDOMElement() ``` -------------------------------- ### Format Array to Sentence Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Use this function to join an array of strings into a human-readable sentence. Customize the connectors for different grammatical structures. ```javascript function toSentence(array, {wordConnector, lastWordConnector} = {}) { const wc = wordConnector === undefined ? ', ' : wordConnector const lwc = lastWordConnector === undefined ? ' and ' : lastWordConnector if (array.length === 1) { return array[0] } return array.slice(0, -1).join(wc) + lwc + array.slice(-1)[0] } ``` ```javascript toSentence(['apple', 'orange', 'banana']) // Returns: "apple, orange and banana" toSentence(['a', 'b'], {lastWordConnector: ' or '}) // Returns: "a or b" toSentence(['single']) // Returns: "single" ``` -------------------------------- ### toHaveAccessibleDescription Source: https://github.com/testing-library/jest-dom/blob/main/README.md Asserts that an element has the expected accessible description. You can provide an exact string, a regular expression, or use Jest's `stringContaining` or `stringMatching`. ```APIDOC ## `toHaveAccessibleDescription` ### Description Asserts that an element has the expected accessible description. You can provide an exact string, a regular expression, or use Jest's `stringContaining` or `stringMatching`. ### Method ```typescript testElement.toHaveAccessibleDescription(expectedAccessibleDescription?: string | RegExp) ``` ### Parameters #### Path Parameters - **expectedAccessibleDescription** (string | RegExp) - Optional. The expected accessible description or a RegExp to match against. ### Examples ```javascript // Assuming an element with an accessible description like aria-label="Close button" expect(getByRole('button')).toHaveAccessibleDescription('Close button') expect(getByRole('button')).toHaveAccessibleDescription(/close/i) ``` ``` -------------------------------- ### compareAsSet() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Compares two values to determine if they are equal when treated as sets. It handles arrays by ignoring duplicates and order, and falls back to strict equality for non-array types. ```APIDOC ## compareAsSet() ### Description Compares two values to determine if they are equal when treated as sets. It handles arrays by ignoring duplicates and order, and falls back to strict equality for non-array types. ### Signature ```javascript function compareAsSet(val1, val2) ``` ### Parameters #### Path Parameters - **val1** (any) - Required - First value to compare - **val2** (any) - Required - Second value to compare ### Return boolean - True if values are equal as sets ### Behavior 1. If both are arrays, checks if all elements in val1 exist in val2 (set subset) 2. Otherwise performs strict equality comparison (===) 3. Ignores duplicates in arrays 4. Ignores element order in arrays ### Request Example ```javascript compareAsSet([1, 2], [1, 2, 3]) // Returns: true (subset) compareAsSet([1, 2], [2, 1]) // Returns: true (same set, order ignored) compareAsSet([1, 2, 3], [1, 2]) // Returns: false (val1 not subset of val2) compareAsSet('text', 'text') // Returns: true (equality) ``` ``` -------------------------------- ### toHaveAccessibleDescription Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/aria-and-accessibility.md Computes the accessible description using W3C algorithms. The description can come from `aria-describedby`, `title` attribute, associated caption or legend elements, or other semantic HTML associations. An element can have both an accessible name and a description. The description provides additional context beyond the name. ```APIDOC ## toHaveAccessibleDescription() ### Description Computes the accessible description using W3C algorithms. The description can come from: 1. `aria-describedby` - References to elements containing the description 2. `title` attribute 3. Associated caption or legend elements 4. Other semantic HTML associations An element can have both an accessible name and a description. The description provides additional context beyond the name. ### Signature ```typescript toHaveAccessibleDescription(text?: string | RegExp): void ``` ### Parameters #### Path Parameters - **text** (string or RegExp) - Optional - Expected accessible description. If omitted, checks that any exists ### Request Example ```javascript // From aria-describedby const input = document.createElement('input') const description = document.createElement('div') description.id = 'help-text' description.textContent = 'Password must be 8+ characters' input.setAttribute('aria-describedby', 'help-text') expect(input).toHaveAccessibleDescription('Password must be 8+ characters') // From title attribute const link = document.createElement('a') link.title = 'Go to the home page' expect(link).toHaveAccessibleDescription('Go to the home page') // Partial match expect(input).toHaveAccessibleDescription(/password/) // Check existence expect(input).toHaveAccessibleDescription() ``` ### Response #### Success Response (200) Matcher result (pass/fail with message) #### Response Example (No specific example provided for response structure, but it indicates pass/fail with message) ### Throws `HtmlElementTypeError` if element is invalid ``` -------------------------------- ### Standalone Matchers for Jest Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/README.md Import and extend Jest's expect with standalone matchers from jest-dom. ```javascript import matchers from '@testing-library/jest-dom/matchers' expect.extend(matchers) ``` -------------------------------- ### matches() Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/utility-functions.md Checks if a given text matches a specified matcher (string or RegExp). Uses `.includes()` for substring matching or `.test()` for regular expressions. ```APIDOC ## matches() ### Description Checks if a given text matches a specified matcher (string or RegExp). Uses `.includes()` for substring matching or `.test()` for regular expressions. ### Signature ```javascript function matches(textToMatch, matcher) ``` ### Parameters #### Path Parameters - **textToMatch** (string) - Required - Text to match against - **matcher** (string or RegExp) - Required - Pattern to match ### Return boolean - True if matcher matches textToMatch ### Example ```javascript matches('Hello World', 'World') // Returns: true matches('Hello World', /^Hello/) // Returns: true matches('Hello World', 'xyz') // Returns: false ``` ``` -------------------------------- ### toAppearBefore Source: https://github.com/testing-library/jest-dom/blob/main/README.md Checks if a given element appears before another element in the DOM tree. ```APIDOC ## toAppearBefore ### Description This checks if a given element appears before another element in the DOM tree, as per [`compareDocumentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). ### Method ```typescript toAppearBefore() ``` ### Examples ```javascript const textA = queryByTestId('text-a') const textB = queryByTestId('text-b') expect(textA).toAppearBefore(textB) expect(textB).not.toAppearBefore(textA) ``` > Note: This matcher does not take into account CSS styles that may modify the > display order of elements, eg: > > - `flex-direction: row-reverse`, > - `flex-direction: column-reverse`, > - `display: grid` ``` -------------------------------- ### Assert Element is Visible Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/api-reference-dom-matchers.md Use `toBeVisible` to verify an element is visible to the user. This checks multiple conditions including CSS properties, attributes, and parent visibility. ```javascript const visible = document.querySelector('[data-testid="visible"]') const hidden = document.querySelector('[data-testid="hidden"]') expect(visible).toBeVisible() expect(hidden).not.toBeVisible() ``` -------------------------------- ### toHaveAccessibleDescription Source: https://github.com/testing-library/jest-dom/blob/main/_autodocs/api-reference-dom-matchers.md Asserts that an element has an accessible description. This can be checked via `aria-describedby`, `title` attributes, or semantic HTML attributes. If no specific description is provided, it verifies that any description exists. ```APIDOC ## toHaveAccessibleDescription() ### Description Asserts that an element has an accessible description. If no expected description is provided, verifies a non-empty description exists. ### Method Signature ```typescript toHaveAccessibleDescription(text?: string | RegExp): void ``` ### Parameters #### text - **text** (string or RegExp) - Optional - Expected accessible description. If omitted, checks that any description exists. ### Throws - `HtmlElementTypeError` if the element is not a valid HTMLElement or SVGElement. ### Example ```javascript const link = document.querySelector('a') expect(link).toHaveAccessibleDescription('A link to the home page') const button = document.querySelector('button') expect(button).toHaveAccessibleDescription(/important/) expect(button).toHaveAccessibleDescription() ``` ``` -------------------------------- ### toHaveRole Source: https://github.com/testing-library/jest-dom/blob/main/README.md Asserts that an element has the expected ARIA role, either explicit or implicit. Roles are matched literally by string equality. ```APIDOC ## `toHaveRole` ### Description This allows you to assert that an element has the expected [role](https://www.w3.org/TR/html-aria/#docconformance). This is useful in cases where you already have access to an element via some query other than the role itself, and want to make additional assertions regarding its accessibility. The role can match either an explicit role (via the `role` attribute), or an implicit one via the [implicit ARIA semantics](https://www.w3.org/TR/html-aria/). Note: roles are matched literally by string equality, without inheriting from the ARIA role hierarchy. As a result, querying a superclass role like 'checkbox' will not include elements with a subclass role like 'switch'. ### Method Signature ```typescript haveRole(expectedRole: string) ``` ### Examples ```javascript // Assuming getByTestId is available expect(getByTestId('button')).toHaveRole('button') expect(getByTestId('button-explicit')).toHaveRole('button') expect(getByTestId('button-explicit-multiple')).toHaveRole('button') expect(getByTestId('button-explicit-multiple')).toHaveRole('switch') expect(getByTestId('link')).toHaveRole('link') expect(getByTestId('link-invalid')).not.toHaveRole('link') expect(getByTestId('link-invalid')).toHaveRole('generic') ``` ```