# jest-dom

Custom jest matchers to test the state of the DOM

--- [![Build Status][build-badge]][build] [![Code Coverage][coverage-badge]][coverage] [![version][version-badge]][package] [![downloads][downloads-badge]][npmtrends] [![MIT License][license-badge]][license] [![All Contributors](https://img.shields.io/badge/all_contributors-28-orange.svg?style=flat-square)](#contributors-) [![PRs Welcome][prs-badge]][prs] [![Code of Conduct][coc-badge]][coc] [![Discord][discord-badge]][discord] [![Watch on GitHub][github-watch-badge]][github-watch] [![Star on GitHub][github-star-badge]][github-star] [![Tweet][twitter-badge]][twitter] ## The problem You want to use [jest][] to write tests that assert various things about the state of a DOM. As part of that goal, you want to avoid all the repetitive patterns that arise in doing so. Checking for an element's attributes, its text content, its css classes, you name it. ## This solution The `@testing-library/jest-dom` library provides a set of custom jest matchers that you can use to extend jest. These will make your tests more declarative, clear to read and to maintain. ## Table of Contents - [Installation](#installation) - [Usage](#usage) - [With `@jest/globals`](#with-jestglobals) - [With Vitest](#with-vitest) - [With TypeScript](#with-typescript) - [With another Jest-compatible `expect`](#with-another-jest-compatible-expect) - [Custom matchers](#custom-matchers) - [`toBeDisabled`](#tobedisabled) - [`toBeEnabled`](#tobeenabled) - [`toBeEmptyDOMElement`](#tobeemptydomelement) - [`toBeInTheDocument`](#tobeinthedocument) - [`toBeInvalid`](#tobeinvalid) - [`toBeRequired`](#toberequired) - [`toBeValid`](#tobevalid) - [`toBeVisible`](#tobevisible) - [`toContainElement`](#tocontainelement) - [`toContainHTML`](#tocontainhtml) - [`toHaveAccessibleDescription`](#tohaveaccessibledescription) - [`toHaveAccessibleErrorMessage`](#tohaveaccessibleerrormessage) - [`toHaveAccessibleName`](#tohaveaccessiblename) - [`toHaveAttribute`](#tohaveattribute) - [`toHaveClass`](#tohaveclass) - [`toHaveFocus`](#tohavefocus) - [`toHaveFormValues`](#tohaveformvalues) - [`toHaveStyle`](#tohavestyle) - [`toHaveTextContent`](#tohavetextcontent) - [`toHaveValue`](#tohavevalue) - [`toHaveDisplayValue`](#tohavedisplayvalue) - [`toBeChecked`](#tobechecked) - [`toBePartiallyChecked`](#tobepartiallychecked) - [`toHaveRole`](#tohaverole) - [`toHaveErrorMessage`](#tohaveerrormessage) - [`toBePressed`](#tobepressed) - [`toBePartiallyPressed`](#tobepartiallypressed) - [`toAppearBefore`](#toappearbefore) - [`toAppearAfter`](#toappearafter) - [Deprecated matchers](#deprecated-matchers) - [`toBeEmpty`](#tobeempty) - [`toBeInTheDOM`](#tobeinthedom) - [`toHaveDescription`](#tohavedescription) - [`toHaveSelection`](#tohaveselection) - [Inspiration](#inspiration) - [Other Solutions](#other-solutions) - [Guiding Principles](#guiding-principles) - [Contributors](#contributors) - [LICENSE](#license) ## Installation This module is distributed via [npm][npm] which is bundled with [node][node] and should be installed as one of your project's `devDependencies`: ``` npm install --save-dev @testing-library/jest-dom ``` or for installation with [yarn](https://yarnpkg.com/) package manager. ``` yarn add --dev @testing-library/jest-dom ``` > Note: We also recommend installing the jest-dom eslint plugin which provides > auto-fixable lint rules that prevent false positive tests and improve test > readability by ensuring you are using the right matchers in your tests. More > details can be found at > [eslint-plugin-jest-dom](https://github.com/testing-library/eslint-plugin-jest-dom). ## Usage Import `@testing-library/jest-dom` once (for instance in your [tests setup file][]) and you're good to go: [tests setup file]: https://jestjs.io/docs/en/configuration.html#setupfilesafterenv-array ```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'] ``` ### 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 ### 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 ### 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" ], ``` ### 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) ``` ## Custom matchers `@testing-library/jest-dom` can work with any library or framework that returns DOM elements from queries. The custom matcher examples below are written using matchers from `@testing-library`'s suite of libraries (e.g. `getByTestId`, `queryByTestId`, `getByText`, etc.) ### `toBeDisabled` ```typescript toBeDisabled() ``` This allows you to check whether an element is disabled from the user's perspective. According to the specification, the following elements can be [disabled](https://html.spec.whatwg.org/multipage/semantics-other.html#disabled-elements): `button`, `input`, `select`, `textarea`, `optgroup`, `option`, `fieldset`, and custom elements. This custom matcher considers an element as disabled if the element is among the types of elements that can be disabled (listed above), and the `disabled` attribute is present. It will also consider the element as disabled if it's inside a parent form element that supports being disabled and has the `disabled` attribute present. #### Examples ```html
link ``` ```javascript expect(getByTestId('button')).toBeDisabled() expect(getByTestId('input')).toBeDisabled() expect(getByText('link')).not.toBeDisabled() ``` > This custom matcher does not take into account the presence or absence of the > `aria-disabled` attribute. For more on why this is the case, check > [#144](https://github.com/testing-library/jest-dom/issues/144).

### `toBeEnabled` ```typescript toBeEnabled() ``` This allows you to check whether an element is not disabled from the user's perspective. It works like `not.toBeDisabled()`. Use this matcher to avoid double negation in your tests. > This custom matcher does not take into account the presence or absence of the > `aria-disabled` attribute. For more on why this is the case, check > [#144](https://github.com/testing-library/jest-dom/issues/144).

### `toBeEmptyDOMElement` ```typescript toBeEmptyDOMElement() ``` This allows you to assert whether an element has no visible content for the user. It ignores comments but will fail if the element contains white-space. #### Examples ```html ``` ```javascript expect(getByTestId('empty')).toBeEmptyDOMElement() expect(getByTestId('not-empty')).not.toBeEmptyDOMElement() expect(getByTestId('with-whitespace')).not.toBeEmptyDOMElement() ```

### `toBeInTheDocument` ```typescript toBeInTheDocument() ``` This allows you to assert whether an element is present in the document or not. #### Examples ```html Html Element
``` ```javascript expect( getByTestId(document.documentElement, 'html-element'), ).toBeInTheDocument() expect(getByTestId(document.documentElement, 'svg-element')).toBeInTheDocument() expect( queryByTestId(document.documentElement, 'does-not-exist'), ).not.toBeInTheDocument() ``` > Note: This matcher does not find detached elements. The element must be added > to the document to be found by toBeInTheDocument. If you desire to search in a > detached element please use: [`toContainElement`](#tocontainelement)

### `toBeInvalid` ```typescript toBeInvalid() ``` This allows you to check if an element, is currently invalid. An element is invalid if it has an [`aria-invalid` attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute) with no value or a value of `"true"`, or if the result of [`checkValidity()`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation) is `false`. #### Examples ```html ``` ```javascript expect(getByTestId('no-aria-invalid')).not.toBeInvalid() expect(getByTestId('aria-invalid')).toBeInvalid() expect(getByTestId('aria-invalid-value')).toBeInvalid() expect(getByTestId('aria-invalid-false')).not.toBeInvalid() expect(getByTestId('valid-form')).not.toBeInvalid() expect(getByTestId('invalid-form')).toBeInvalid() ```

### `toBeRequired` ```typescript toBeRequired() ``` This allows you to check if a form element is currently required. An element is required if it is having a `required` or `aria-required="true"` attribute. #### Examples ```html
``` ```javascript expect(getByTestId('required-input')).toBeRequired() expect(getByTestId('aria-required-input')).toBeRequired() expect(getByTestId('conflicted-input')).toBeRequired() expect(getByTestId('aria-not-required-input')).not.toBeRequired() expect(getByTestId('optional-input')).not.toBeRequired() expect(getByTestId('unsupported-type')).not.toBeRequired() expect(getByTestId('select')).toBeRequired() expect(getByTestId('textarea')).toBeRequired() expect(getByTestId('supported-role')).not.toBeRequired() expect(getByTestId('supported-role-aria')).toBeRequired() ```

### `toBeValid` ```typescript toBeValid() ``` This allows you to check if the value of an element, is currently valid. An element is valid if it has no [`aria-invalid` attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute)s or an attribute value of `"false"`. The result of [`checkValidity()`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation) must also be `true` if it's a form element. #### Examples ```html ``` ```javascript expect(getByTestId('no-aria-invalid')).toBeValid() expect(getByTestId('aria-invalid')).not.toBeValid() expect(getByTestId('aria-invalid-value')).not.toBeValid() expect(getByTestId('aria-invalid-false')).toBeValid() expect(getByTestId('valid-form')).toBeValid() expect(getByTestId('invalid-form')).not.toBeValid() ```

### `toBeVisible` ```typescript toBeVisible() ``` This allows you to check if an element is currently visible to the user. An element is visible if **all** the following conditions are met: - it is present in the document - it does not have its css property `display` set to `none` - it does not have its css property `visibility` set to either `hidden` or `collapse` - it does not have its css property `opacity` set to `0` - its parent element is also visible (and so on up to the top of the DOM tree) - it does not have the [`hidden`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) attribute - if `
` it has the `open` attribute #### Examples ```html
Zero Opacity Example
Visibility Hidden Example
Display None Example
Hidden Parent Example
Visible Example
Hidden Attribute 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() ```

### `toContainElement` ```typescript toContainElement(element: HTMLElement | SVGElement | null) ``` This allows you to assert whether an element contains another element as a descendant or not. #### Examples ```html ``` ```javascript const ancestor = getByTestId('ancestor') const descendant = getByTestId('descendant') const nonExistantElement = getByTestId('does-not-exist') expect(ancestor).toContainElement(descendant) expect(descendant).not.toContainElement(ancestor) expect(ancestor).not.toContainElement(nonExistantElement) ```

### `toContainHTML` ```typescript toContainHTML(htmlText: string) ``` Assert whether a string representing a HTML element is contained in another element. The string should contain valid html, and not any incomplete html. #### Examples ```html ``` ```javascript // These are valid uses expect(getByTestId('parent')).toContainHTML('') expect(getByTestId('parent')).toContainHTML('') expect(getByTestId('parent')).not.toContainHTML('
') // These won't work expect(getByTestId('parent')).toContainHTML('data-testid="child"') expect(getByTestId('parent')).toContainHTML('data-testid') expect(getByTestId('parent')).toContainHTML('') ``` > Chances are you probably do not need to use this matcher. We encourage testing > from the perspective of how the user perceives the app in a browser. That's > why testing against a specific DOM structure is not advised. > > It could be useful in situations where the code being tested renders html that > was obtained from an external source, and you want to validate that that html > code was used as intended. > > It should not be used to check DOM structure that you control. Please use > [`toContainElement`](#tocontainelement) instead.

### `toHaveAccessibleDescription` ```typescript toHaveAccessibleDescription(expectedAccessibleDescription?: string | RegExp) ``` This allows you to assert that an element has the expected [accessible description](https://w3c.github.io/accname/). You can pass the exact string of the expected accessible description, or you can make a partial match passing a regular expression, or by using [expect.stringContaining](https://jestjs.io/docs/en/expect.html#expectnotstringcontainingstring)/[expect.stringMatching](https://jestjs.io/docs/en/expect.html#expectstringmatchingstring-regexp). #### Examples ```html Start About The logo of Our Company ``` ```js expect(getByTestId('link')).toHaveAccessibleDescription() expect(getByTestId('link')).toHaveAccessibleDescription('A link to start over') expect(getByTestId('link')).not.toHaveAccessibleDescription('Home page') expect(getByTestId('extra-link')).not.toHaveAccessibleDescription() expect(getByTestId('avatar')).not.toHaveAccessibleDescription() expect(getByTestId('logo')).not.toHaveAccessibleDescription('Company logo') expect(getByTestId('logo')).toHaveAccessibleDescription( 'The logo of Our Company', ) expect(getByTestId('logo2')).toHaveAccessibleDescription( 'The logo of Our Company', ) ```

### `toHaveAccessibleErrorMessage` ```typescript toHaveAccessibleErrorMessage(expectedAccessibleErrorMessage?: string | RegExp) ``` This allows you to assert that an element has the expected [accessible error message](https://w3c.github.io/aria/#aria-errormessage). You can pass the exact string of the expected accessible error message. Alternatively, you can perform a partial match by passing a regular expression or by using [expect.stringContaining](https://jestjs.io/docs/en/expect.html#expectnotstringcontainingstring)/[expect.stringMatching](https://jestjs.io/docs/en/expect.html#expectstringmatchingstring-regexp). #### Examples ```html
This field is invalid
``` ```js // Inputs with Valid Error Messages expect(getByRole('textbox', {name: 'Has Error'})).toHaveAccessibleErrorMessage() expect(getByRole('textbox', {name: 'Has Error'})).toHaveAccessibleErrorMessage( 'This field is invalid', ) expect(getByRole('textbox', {name: 'Has Error'})).toHaveAccessibleErrorMessage( /invalid/i, ) expect( getByRole('textbox', {name: 'Has Error'}), ).not.toHaveAccessibleErrorMessage('This field is absolutely correct!') // Inputs without Valid Error Messages expect( getByRole('textbox', {name: 'No Error Attributes'}), ).not.toHaveAccessibleErrorMessage() expect( getByRole('textbox', {name: 'Not Invalid'}), ).not.toHaveAccessibleErrorMessage() ```

### `toHaveAccessibleName` ```typescript toHaveAccessibleName(expectedAccessibleName?: string | RegExp) ``` This allows you to assert that an element has the expected [accessible name](https://w3c.github.io/accname/). It is useful, for instance, to assert that form elements and buttons are properly labelled. You can pass the exact string of the expected accessible name, or you can make a partial match passing a regular expression, or by using [expect.stringContaining](https://jestjs.io/docs/en/expect.html#expectnotstringcontainingstring)/[expect.stringMatching](https://jestjs.io/docs/en/expect.html#expectstringmatchingstring-regexp). #### Examples ```html

Test content

About Invalid link ``` ```javascript 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') ```

### `toHaveErrorMessage` > This custom matcher is deprecated. Prefer > [`toHaveAccessibleErrorMessage`](#tohaveaccessibleerrormessage) instead, which > is more comprehensive in implementing the official spec. ```typescript toHaveErrorMessage(text: string | RegExp) ``` This allows you to check whether the given element has an [ARIA error message](https://www.w3.org/TR/wai-aria/#aria-errormessage) or not. Use the `aria-errormessage` attribute to reference another element that contains custom error message text. Multiple ids is **NOT** allowed. Authors MUST use `aria-invalid` in conjunction with `aria-errormessage`. Learn more from [`aria-errormessage` spec](https://www.w3.org/TR/wai-aria/#aria-errormessage). Whitespace is normalized. When a `string` argument is passed through, it will perform a whole case-sensitive match to the error message text. To perform a case-insensitive match, you can use a `RegExp` with the `/i` modifier. To perform a partial match, you can pass a `RegExp` or use `expect.stringContaining("partial string")`. #### Examples ```html Please enter a start time for the meeting: Invalid time: the time must be between 9:00 AM and 5:00 PM ``` ```javascript const timeInput = getByLabel('startTime') expect(timeInput).toHaveErrorMessage( 'Invalid time: the time must be between 9:00 AM and 5:00 PM', ) expect(timeInput).toHaveErrorMessage(/invalid time/i) // to partially match expect(timeInput).toHaveErrorMessage(expect.stringContaining('Invalid time')) // to partially match expect(timeInput).not.toHaveErrorMessage('Pikachu!') ```

### `toBePressed` This allows to check whether given element is [pressed](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed). It accepts elements with explicit or implicit `button` role and valid `aria-pressed` attribute of `"true"` or `"false"`. ```typescript toBePressed() ``` #### Examples ```html
Pressed span Released span ``` ##### Using DOM Testing Library ```javascript screen.getByRole('button', {name: 'Pressed'}).toBePressed() screen.getByRole('button', {name: 'Released'}).not.toBePressed() screen.getByRole('button', {name: 'Pressed input button'}).toBePressed() screen.getByRole('button', {name: 'Released input button'}).not.toBePressed() screen.getByRole('button', {name: 'Pressed span'}).toBePressed() screen.getByRole('button', {name: 'Released span'}).not.toBePressed() ```

### `toBePartiallyPressed` This allows to check whether given element is partially [pressed](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed). It accepts elements with explicit or implicit `button` role and valid `aria-pressed` attribute of `mixed`. ```typescript toBePressed() ``` #### Examples ```html
Partially pressed span ``` ##### Using DOM Testing Library ```javascript screen.getByRole('button', {name: 'Partially pressed'}).toBePartiallyPressed() screen .getByRole('button', {name: 'Partially pressed input button'}) .toBePartiallyPressed() screen .getByRole('button', {name: 'Partially pressed span'}) .toBePartiallyPressed() ```

### `toAppearBefore` 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). ```typescript toAppearBefore() ``` #### Examples ```html
Text A Text B
``` ```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` ### `toAppearAfter` This checks if a given element appears after another element in the DOM tree, as per [`compareDocumentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition). ```typescript toAppearAfter() ``` #### Examples ```html
Text A Text B
``` ```javascript const textA = queryByTestId('text-a') const textB = queryByTestId('text-b') expect(textB).toAppearAfter(textA) expect(textA).not.toAppearAfter(textB) ``` > Note: This matcher does not take into account CSS styles that may modify the > display order of elements, see [`toAppearBefore()`](#toappearbefore) ## Deprecated matchers ### `toBeEmpty` > Note: This matcher is being deprecated due to a name clash with > `jest-extended`. See more info in #216. In the future, please use only > [`toBeEmptyDOMElement`](#toBeEmptyDOMElement) ```typescript toBeEmpty() ``` This allows you to assert whether an element has content or not. #### Examples ```html ``` ```javascript expect(getByTestId('empty')).toBeEmpty() expect(getByTestId('not-empty')).not.toBeEmpty() ```

### `toBeInTheDOM` > This custom matcher is deprecated. Prefer > [`toBeInTheDocument`](#tobeinthedocument) instead. ```typescript toBeInTheDOM() ``` This allows you to check whether a value is a DOM element, or not. Contrary to what its name implies, this matcher only checks that you passed to it a valid DOM element. It does not have a clear definition of what "the DOM" is. Therefore, it does not check whether that element is contained anywhere. This is the main reason why this matcher is deprecated, and will be removed in the next major release. You can follow the discussion around this decision in more detail [here](https://github.com/testing-library/jest-dom/issues/34). As an alternative, you can use [`toBeInTheDocument`](#tobeinthedocument) or [`toContainElement`](#tocontainelement). Or if you just want to check if a value is indeed an `HTMLElement` you can always use some of [jest's built-in matchers](https://jestjs.io/docs/en/expect#tobeinstanceofclass): ```js expect(document.querySelector('.ok-button')).toBeInstanceOf(HTMLElement) expect(document.querySelector('.cancel-button')).toBeTruthy() ``` > Note: The differences between `toBeInTheDOM` and `toBeInTheDocument` are > significant. Replacing all uses of `toBeInTheDOM` with `toBeInTheDocument` > will likely cause unintended consequences in your tests. Please make sure when > replacing `toBeInTheDOM` to read through the documentation of the proposed > alternatives to see which use case works better for your needs.

### `toHaveDescription` > This custom matcher is deprecated. Prefer > [`toHaveAccessibleDescription`](#tohaveaccessibledescription) instead, which > is more comprehensive in implementing the official spec. ```typescript toHaveDescription(text: string | RegExp) ``` This allows you to check whether the given element has a description or not. An element gets its description via the [`aria-describedby` attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-describedby_attribute). Set this to the `id` of one or more other elements. These elements may be nested inside, be outside, or a sibling of the passed in element. Whitespace is normalized. Using multiple ids will [join the referenced elements’ text content separated by a space](https://www.w3.org/TR/accname-1.1/#mapping_additional_nd_description). When a `string` argument is passed through, it will perform a whole case-sensitive match to the description text. To perform a case-insensitive match, you can use a `RegExp` with the `/i` modifier. To perform a partial match, you can pass a `RegExp` or use `expect.stringContaining("partial string")`. #### Examples ```html
Closing will discard any changes
``` ```javascript const closeButton = getByRole('button', {name: 'Close'}) expect(closeButton).toHaveDescription('Closing will discard any changes') expect(closeButton).toHaveDescription(/will discard/) // to partially match expect(closeButton).toHaveDescription(expect.stringContaining('will discard')) // to partially match expect(closeButton).toHaveDescription(/^closing/i) // to use case-insensitive match expect(closeButton).not.toHaveDescription('Other description') const deleteButton = getByRole('button', {name: 'Delete'}) expect(deleteButton).not.toHaveDescription() expect(deleteButton).toHaveDescription('') // Missing or empty description always becomes a blank string ```

### `toHaveSelection` This allows to assert that an element has a [text selection](https://developer.mozilla.org/en-US/docs/Web/API/Selection). This is useful to check if text or part of the text is selected within an element. The element can be either an input of type text, a textarea, or any other element that contains text, such as a paragraph, span, div etc. NOTE: the expected selection is a string, it does not allow to check for selection range indeces. ```typescript toHaveSelection(expectedSelection?: string) ``` ```html
text selected text

prev

text selected text

next

``` ```javascript getByTestId('text').setSelectionRange(5, 13) expect(getByTestId('text')).toHaveSelection('selected') getByTestId('textarea').setSelectionRange(0, 5) expect('textarea').toHaveSelection('text ') const selection = document.getSelection() const range = document.createRange() selection.removeAllRanges() selection.empty() selection.addRange(range) // selection of child applies to the parent as well range.selectNodeContents(getByTestId('child')) expect(getByTestId('child')).toHaveSelection('selected') expect(getByTestId('parent')).toHaveSelection('selected') // selection that applies from prev all, parent text before child, and part child. range.setStart(getByTestId('prev'), 0) range.setEnd(getByTestId('child').childNodes[0], 3) expect(queryByTestId('prev')).toHaveSelection('prev') expect(queryByTestId('child')).toHaveSelection('sel') expect(queryByTestId('parent')).toHaveSelection('text sel') expect(queryByTestId('next')).not.toHaveSelection() // selection that applies from part child, parent text after child and part next. range.setStart(getByTestId('child').childNodes[0], 3) range.setEnd(getByTestId('next').childNodes[0], 2) expect(queryByTestId('child')).toHaveSelection('ected') expect(queryByTestId('parent')).toHaveSelection('ected text') expect(queryByTestId('prev')).not.toHaveSelection() expect(queryByTestId('next')).toHaveSelection('ne') ``` ## Inspiration This whole library was extracted out of Kent C. Dodds' [DOM Testing Library][dom-testing-library], which was in turn extracted out of [React Testing Library][react-testing-library]. The intention is to make this available to be used independently of these other libraries, and also to make it more clear that these other libraries are independent from jest, and can be used with other tests runners as well. ## Other Solutions I'm not aware of any, if you are please [make a pull request][prs] and add it here! If you would like to further test the accessibility and validity of the DOM consider [`jest-axe`](https://github.com/nickcolley/jest-axe). It doesn't overlap with `jest-dom` but can complement it for more in-depth accessibility checking (eg: validating `aria` attributes or ensuring unique id attributes). ## Guiding Principles > [The more your tests resemble the way your software is used, the more > confidence they can give you.][guiding-principle] This library follows the same guiding principles as its mother library [DOM Testing Library][dom-testing-library]. Go [check them out][guiding-principle] for more details. Additionally, with respect to custom DOM matchers, this library aims to maintain a minimal but useful set of them, while avoiding bloating itself with merely convenient ones that can be easily achieved with other APIs. In general, the overall criteria for what is considered a useful custom matcher to add to this library, is that doing the equivalent assertion on our own makes the test code more verbose, less clear in its intent, and/or harder to read. ## Contributors Thanks goes to these people ([emoji key][emojis]):

Kent C. Dodds 💻 📖 🚇 ⚠️ | Ryan Castner 📖 | Daniel Sandiego 💻 | Paweł Mikołajczyk 💻 | Alejandro Ñáñez Ortiz 📖 | Matt Parrish 🐛 💻 📖 ⚠️ | Justin Hall 📦
Anto Aravinth 💻 ⚠️ 📖 | Jonah Moses 📖 | Łukasz Gandecki 💻 ⚠️ 📖 | Ivan Babak 🐛 🤔 | Jesse Day 💻 | Ernesto García 💻 📖 ⚠️ | Mark Volkmann 🐛 💻
smacpherson64 💻 📖 ⚠️ | John Gozde 🐛 💻 | Iwona 💻 📖 ⚠️ | Lewis 💻 | Leandro Lourenci 🐛 📖 💻 ⚠️ | Shukhrat Mukimov 🐛 | Roman Usherenko 💻 ⚠️
Joe Hsu 📖 | Haz 🐛 💻 🤔 | Revath S Kumar 💻 | hiwelo. 💻 🤔 ⚠️ | Łukasz Fiszer 💻 | Jean Chung 💻 ⚠️ | CarlaTeo 💻 ⚠️
Yarden Shoham 📖 | Jaga Santagostino 🐛 ⚠️ 📖 | Connor Meredith 💻 ⚠️ 📖 | Pawel Wolak ⚠️ 💻 | Michaël De Boey 🚇 | Jānis Zaržeckis 📖 | koala-lava 📖
Juan Pablo Blanco 📖 | Ben Monro 📖 | Jeff Bernstein 📖 | Sergi 💻 ⚠️ | Spencer Miskoviak 📖 | Jon Rimmer 💻 ⚠️ | Luca Barone 💻 ⚠️ 🤔
Malte Felmy 💻 ⚠️ | Championrunner 📖 | Patrick Smith 💻 ⚠️ 📖 | Rubén Moya 💻 ⚠️ 📖 | Daniela Valero 💻 ⚠️ 📖 | Vladislav Katsura 💻 ⚠️ | Tim Fischbach 💻 ⚠️ 🤔
Katie Boedges 🚇 | Brian Alexis ⚠️ | Boris Serdiuk 🐛 💻 ⚠️ | Dana Woodman 📖 | Mo Sattler 📖 | Geoff Rich 💻 ⚠️ 🤔 🐛 | Syneva 💻
Nick McCurdy 📖 🐛 💻 | Obed Marquez Parlapiano 📖 | Caleb Eby 📖 💻 ⚠️ | Marcel Barner 💻 ⚠️ | Doma 💻 ⚠️ | Julien Wajsberg 💻 ⚠️ | steven nguyen 📖
tu4mo 📖 | Matan Borenkraout 📦 | Yann Braga 💻 | Ian VanSchooten 💻 | Chantal Broeren 📖 | Jérémie Astori 💻 🤔 | Ashley Ryan 💻 🤔
Fotis Papadogeorgopoulos 💻 📖 ⚠️ | Jake Boone 💻 ⚠️ | Stephan Köninger 🐛 💻 | Michael Manzinger 🐛 💻 ⚠️ | Dennis Chen 💻 | Tony Hallett 🐛 | David DOLCIMASCOLO 🚧
Aleksandr Elkin 🚧 | Mordechai Dror 💻 | Wayne Van Son 💻 ⚠️ | Idan Entin 💻 ⚠️ | mibcadet 📖 | Silviu Alexandru Avram 💻 ⚠️ | Gareth Jones 💻
Billy Janitsch 🐛 | InfiniteXyy 💻 🐛 | Marcin Kulpa 💻 ⚠️ | Gibson C 💻 ⚠️

This project follows the [all-contributors][all-contributors] specification. Contributions of any kind welcome! ## LICENSE MIT [jest]: https://facebook.github.io/jest/ [dom-testing-library]: https://github.com/testing-library/dom-testing-library [react-testing-library]: https://github.com/testing-library/react-testing-library [npm]: https://www.npmjs.com/ [node]: https://nodejs.org [build-badge]: https://img.shields.io/github/actions/workflow/status/testing-library/jest-dom/validate.yml?branch=main&logo=github&style=flat-square [build]: https://github.com/testing-library/jest-dom/actions?query=workflow%3Avalidate [coverage-badge]: https://img.shields.io/codecov/c/github/testing-library/jest-dom.svg?style=flat-square [coverage]: https://codecov.io/github/testing-library/jest-dom [version-badge]: https://img.shields.io/npm/v/@testing-library/jest-dom.svg?style=flat-square [package]: https://www.npmjs.com/package/@testing-library/jest-dom [downloads-badge]: https://img.shields.io/npm/dm/@testing-library/jest-dom.svg?style=flat-square [npmtrends]: http://www.npmtrends.com/@testing-library/jest-dom [license-badge]: https://img.shields.io/npm/l/@testing-library/jest-dom.svg?style=flat-square [license]: https://github.com/testing-library/jest-dom/blob/main/LICENSE [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square [prs]: http://makeapullrequest.com [coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square [coc]: https://github.com/testing-library/jest-dom/blob/main/other/CODE_OF_CONDUCT.md [github-watch-badge]: https://img.shields.io/github/watchers/testing-library/jest-dom.svg?style=social [github-watch]: https://github.com/testing-library/jest-dom/watchers [github-star-badge]: https://img.shields.io/github/stars/testing-library/jest-dom.svg?style=social [github-star]: https://github.com/testing-library/jest-dom/stargazers [twitter]: https://twitter.com/intent/tweet?text=Check%20out%20jest-dom%20by%20%40gnapse%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fjest-dom%20%F0%9F%91%8D [twitter-badge]: https://img.shields.io/twitter/url/https/github.com/testing-library/jest-dom.svg?style=social [emojis]: https://github.com/all-contributors/all-contributors#emoji-key [all-contributors]: https://github.com/all-contributors/all-contributors [all-contributors-badge]: https://img.shields.io/github/all-contributors/testing-library/jest-dom?color=orange&style=flat-square [guiding-principle]: https://testing-library.com/docs/guiding-principles [discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square [discord]: https://discord.gg/testing-library