GitHub - testing-library/jest-dom: :owl: Custom jest matchers to test the state of the DOM (original) (raw)

jest-dom

owl

Custom jest matchers to test the state of the DOM


Build Status Code Coverage version downloads MIT License

All Contributors PRs Welcome Code of Conduct Discord

Watch on GitHub Star on GitHub Tweet

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

This module is distributed via npm which is bundled with 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 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 ateslint-plugin-jest-dom.

Usage

Import @testing-library/jest-dom once (for instance in your tests setup file) and you're good to go:

// 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 withinjectGlobals: false, you will need to use a different import in your tests setup file:

// In your own jest-setup.js (or any other name) import '@testing-library/jest-dom/jest-globals'

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 property in your vitest config:

// 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 yourtsconfig.json:

// In tsconfig.json "compilerOptions": { ... "types": ["vitest/globals", "@testing-library/jest-dom"] }, "include": [ ... "./vitest.setup.ts" ],

With TypeScript

If you're using TypeScript, make sure your setup file is a .ts and not a .jsto include the necessary types.

You will also need to include your setup file in your tsconfig.json if you haven't already:

// 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 expectinterface, it might be possible to use it with this library:

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

This allows you to check whether an element is disabled from the user's perspective. According to the specification, the following elements can bedisabled: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 disabledattribute 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 disabledattribute present.

Examples

submit

link

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 thearia-disabled attribute. For more on why this is the case, check#144.


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 thearia-disabled attribute. For more on why this is the case, check#144.


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

expect(getByTestId('empty')).toBeEmptyDOMElement() expect(getByTestId('not-empty')).not.toBeEmptyDOMElement() expect(getByTestId('with-whitespace')).not.toBeEmptyDOMElement()


toBeInTheDocument

This allows you to assert whether an element is present in the document or not.

Examples

Html Element

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


toBeInvalid

This allows you to check if an element, is currently invalid.

An element is invalid if it has anaria-invalid attributewith no value or a value of "true", or if the result ofcheckValidity()is false.

Examples

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

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

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

This allows you to check if the value of an element, is currently valid.

An element is valid if it has noaria-invalid attributes or an attribute value of "false". The result ofcheckValidity()must also be true if it's a form element.

Examples

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

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:

Examples

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

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

toContainElement(element: HTMLElement | SVGElement | null)

This allows you to assert whether an element contains another element as a descendant or not.

Examples

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

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

// 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 usetoContainElement instead.


toHaveAccessibleDescription

toHaveAccessibleDescription(expectedAccessibleDescription?: string | RegExp)

This allows you to assert that an element has the expectedaccessible description.

You can pass the exact string of the expected accessible description, or you can make a partial match passing a regular expression, or by usingexpect.stringContaining/expect.stringMatching.

Examples

<a data-testid="link" href="/" aria-label="Home page" title="A link to start over"

Start</a

About User profile pic Company logo The logo of Our Company Company logo

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

toHaveAccessibleErrorMessage(expectedAccessibleErrorMessage?: string | RegExp)

This allows you to assert that an element has the expectedaccessible error message.

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 usingexpect.stringContaining/expect.stringMatching.

Examples

This field is invalid

// 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

toHaveAccessibleName(expectedAccessibleName?: string | RegExp)

This allows you to assert that an element has the expectedaccessible name. 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 usingexpect.stringContaining/expect.stringMatching.

Examples

Test alt Test title Test

Test content

Test

expect(getByTestId('img-alt')).toHaveAccessibleName('Test alt') expect(getByTestId('img-empty-alt')).not.toHaveAccessibleName() expect(getByTestId('svg-title')).toHaveAccessibleName('Test title') expect(getByTestId('button-img-alt')).toHaveAccessibleName() expect(getByTestId('img-paragraph')).not.toHaveAccessibleName() expect(getByTestId('svg-button')).toHaveAccessibleName() expect(getByTestId('svg-without-title')).not.toHaveAccessibleName() expect(getByTestId('input-title')).toHaveAccessibleName()


toHaveAttribute

toHaveAttribute(attr: string, value?: any)

This allows you to check whether the given element has an attribute or not. You can also optionally check that the attribute has a specific expected value or partial match usingexpect.stringContaining/expect.stringMatching

Examples

ok

const button = getByTestId('ok-button')

expect(button).toHaveAttribute('disabled') expect(button).toHaveAttribute('type', 'submit') expect(button).not.toHaveAttribute('type', 'button')

expect(button).toHaveAttribute('type', expect.stringContaining('sub')) expect(button).toHaveAttribute('type', expect.not.stringContaining('but'))


toHaveClass

toHaveClass(...classNames: string[], options?: {exact: boolean})

This allows you to check whether the given element has certain classes within its class attribute. You must provide at least one class, unless you are asserting that an element does not have any classes.

The list of class names may include strings and regular expressions. Regular expressions are matched against each individual class in the target element, and it is NOT matched against its full class attribute value as whole.

Examples

Delete item No Classes

const deleteButton = getByTestId('delete-button') const noClasses = getByTestId('no-classes')

expect(deleteButton).toHaveClass('extra') expect(deleteButton).toHaveClass('btn-danger btn') expect(deleteButton).toHaveClass(/danger/, 'btn') expect(deleteButton).toHaveClass('btn-danger', 'btn') expect(deleteButton).not.toHaveClass('btn-link') expect(deleteButton).not.toHaveClass(/link/) expect(deleteButton).not.toHaveClass(/btn extra/) // It does not match

expect(deleteButton).toHaveClass('btn-danger extra btn', {exact: true}) // to check if the element has EXACTLY a set of classes expect(deleteButton).not.toHaveClass('btn-danger extra', {exact: true}) // if it has more than expected it is going to fail

expect(noClasses).not.toHaveClass()


toHaveFocus

This allows you to assert whether an element has focus or not.

Examples

const input = getByTestId('element-to-focus')

input.focus() expect(input).toHaveFocus()

input.blur() expect(input).not.toHaveFocus()


toHaveFormValues

toHaveFormValues(expectedValues: { [name: string]: any })

This allows you to check if a form or fieldset contains form controls for each given name, and having the specified value.

It is important to stress that this matcher can only be invoked on a formor a fieldset element.

This allows it to take advantage of the .elements property in form andfieldset to reliably fetch all form controls within them.

This also avoids the possibility that users provide a container that contains more than one form, thereby intermixing form controls that are not related, and could even conflict with one another.

This matcher abstracts away the particularities with which a form control value is obtained depending on the type of form control. For instance, <input>elements have a value attribute, but <select> elements do not. Here's a list of all cases covered:

The above rules make it easy, for instance, to switch from using a single select control to using a group of radio buttons. Or to switch from a multi select control, to using a group of checkboxes. The resulting set of form values used by this matcher to compare against would be the same.

Examples

Sign in

expect(getByTestId('login-form')).toHaveFormValues({ username: 'jane.doe', rememberMe: true, })


toHaveStyle

toHaveStyle(css: string | object)

This allows you to check if a certain element has some specific css properties with specific values applied. It matches only if the element has all the expected properties applied, not just some of them.

Examples

<button data-testid="delete-button" style="display: none; background-color: red"

Delete item

const button = getByTestId('delete-button')

expect(button).toHaveStyle('display: none') expect(button).toHaveStyle({display: 'none'}) expect(button).toHaveStyle( background-color: red; display: none;) expect(button).toHaveStyle({ backgroundColor: 'red', display: 'none', }) expect(button).not.toHaveStyle( background-color: blue; display: none;) expect(button).not.toHaveStyle({ backgroundColor: 'blue', display: 'none', })

This also works with rules that are applied to the element via a class name for which some rules are defined in a stylesheet currently active in the document. The usual rules of css precedence apply.


toHaveTextContent

toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean})

This allows you to check whether the given node has a text content or not. This supports elements, but also text nodes and fragments.

When a string argument is passed through, it will perform a partial case-sensitive match to the node content.

To perform a case-insensitive match, you can use a RegExp with the /imodifier.

If you want to match the whole content, you can use a RegExp to do it.

Examples

Text Content

const element = getByTestId('text-content')

expect(element).toHaveTextContent('Content') expect(element).toHaveTextContent(/^Text Content$/) // to match the whole content expect(element).toHaveTextContent(/content$/i) // to use case-insensitive match expect(element).not.toHaveTextContent('content')


toHaveValue

toHaveValue(value: string | string[] | number)

This allows you to check whether the given form element has the specified value. It accepts <input>, <select> and <textarea> elements with the exception of<input type="checkbox"> and <input type="radio">, which can be meaningfully matched only using toBeChecked ortoHaveFormValues.

It also accepts elements with roles meter, progressbar, slider orspinbutton and checks their aria-valuenow attribute (as a number).

For all other form elements, the value is matched using the same algorithm as intoHaveFormValues does.

Examples

Using DOM Testing Library

const textInput = getByTestId('input-text') const numberInput = getByTestId('input-number') const emptyInput = getByTestId('input-empty') const selectInput = getByTestId('select-number')

expect(textInput).toHaveValue('text') expect(numberInput).toHaveValue(5) expect(emptyInput).not.toHaveValue() expect(selectInput).toHaveValue(['second', 'third'])


toHaveDisplayValue

toHaveDisplayValue(value: string | RegExp | (string|RegExp)[])

This allows you to check whether the given form element has the specified displayed value (the one the end user will see). It accepts <input>,<select> and <textarea> elements with the exception of<input type="checkbox"> and <input type="radio">, which can be meaningfully matched only using toBeChecked ortoHaveFormValues.

Examples

First name

Description

Fruit

Fruits

Using DOM Testing Library

const input = screen.getByLabelText('First name') const textarea = screen.getByLabelText('Description') const selectSingle = screen.getByLabelText('Fruit') const selectMultiple = screen.getByLabelText('Fruits')

expect(input).toHaveDisplayValue('Luca') expect(input).toHaveDisplayValue(/Luc/) expect(textarea).toHaveDisplayValue('An example description here.') expect(textarea).toHaveDisplayValue(/example/) expect(selectSingle).toHaveDisplayValue('Select a fruit...') expect(selectSingle).toHaveDisplayValue(/Select/) expect(selectMultiple).toHaveDisplayValue([/Avocado/, 'Banana'])


toBeChecked

This allows you to check whether the given element is checked. It accepts aninput of type checkbox or radio and elements with a role of checkbox,radio or switch with a valid aria-checked attribute of "true" or"false".

Examples

const inputCheckboxChecked = getByTestId('input-checkbox-checked') const inputCheckboxUnchecked = getByTestId('input-checkbox-unchecked') const ariaCheckboxChecked = getByTestId('aria-checkbox-checked') const ariaCheckboxUnchecked = getByTestId('aria-checkbox-unchecked') expect(inputCheckboxChecked).toBeChecked() expect(inputCheckboxUnchecked).not.toBeChecked() expect(ariaCheckboxChecked).toBeChecked() expect(ariaCheckboxUnchecked).not.toBeChecked()

const inputRadioChecked = getByTestId('input-radio-checked') const inputRadioUnchecked = getByTestId('input-radio-unchecked') const ariaRadioChecked = getByTestId('aria-radio-checked') const ariaRadioUnchecked = getByTestId('aria-radio-unchecked') expect(inputRadioChecked).toBeChecked() expect(inputRadioUnchecked).not.toBeChecked() expect(ariaRadioChecked).toBeChecked() expect(ariaRadioUnchecked).not.toBeChecked()

const ariaSwitchChecked = getByTestId('aria-switch-checked') const ariaSwitchUnchecked = getByTestId('aria-switch-unchecked') expect(ariaSwitchChecked).toBeChecked() expect(ariaSwitchUnchecked).not.toBeChecked()


toBePartiallyChecked

This allows you to check whether the given element is partially checked. It accepts an input of type checkbox and elements with a role of checkboxwith a aria-checked="mixed", or input of type checkbox withindeterminate set to true

Examples

const ariaCheckboxMixed = getByTestId('aria-checkbox-mixed') const inputCheckboxChecked = getByTestId('input-checkbox-checked') const inputCheckboxUnchecked = getByTestId('input-checkbox-unchecked') const ariaCheckboxChecked = getByTestId('aria-checkbox-checked') const ariaCheckboxUnchecked = getByTestId('aria-checkbox-unchecked') const inputCheckboxIndeterminate = getByTestId('input-checkbox-indeterminate')

expect(ariaCheckboxMixed).toBePartiallyChecked() expect(inputCheckboxChecked).not.toBePartiallyChecked() expect(inputCheckboxUnchecked).not.toBePartiallyChecked() expect(ariaCheckboxChecked).not.toBePartiallyChecked() expect(ariaCheckboxUnchecked).not.toBePartiallyChecked()

inputCheckboxIndeterminate.indeterminate = true expect(inputCheckboxIndeterminate).toBePartiallyChecked()


toHaveRole

This allows you to assert that an element has the expectedrole.

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 theimplicit ARIA semantics.

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'.

toHaveRole(expectedRole: string)

Continue

Continue Continue About Invalid link

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. PrefertoHaveAccessibleErrorMessage instead, which is more comprehensive in implementing the official spec.

toHaveErrorMessage(text: string | RegExp)

This allows you to check whether the given element has anARIA error message or not.

Use the aria-errormessage attribute to reference another element that contains custom error message text. Multiple ids is NOT allowed. Authors MUST usearia-invalid in conjunction with aria-errormessage. Learn more fromaria-errormessage spec.

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 /imodifier.

To perform a partial match, you can pass a RegExp or useexpect.stringContaining("partial string").

Examples

Please enter a start time for the meeting: Invalid time: the time must be between 9:00 AM and 5:00 PM

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!')

Deprecated matchers

toBeEmpty

Note: This matcher is being deprecated due to a name clash withjest-extended. See more info in #216. In the future, please use onlytoBeEmptyDOMElement

This allows you to assert whether an element has content or not.

Examples

expect(getByTestId('empty')).toBeEmpty() expect(getByTestId('not-empty')).not.toBeEmpty()


toBeInTheDOM

This custom matcher is deprecated. PrefertoBeInTheDocument instead.

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.

As an alternative, you can use toBeInTheDocument ortoContainElement. Or if you just want to check if a value is indeed an HTMLElement you can always use some ofjest's built-in matchers:

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 toBeInTheDocumentwill 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. PrefertoHaveAccessibleDescription instead, which is more comprehensive in implementing the official spec.

toHaveDescription(text: string | RegExp)

This allows you to check whether the given element has a description or not.

An element gets its description via thearia-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 willjoin the referenced elementsโ€™ text content separated by a space.

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 /imodifier.

To perform a partial match, you can pass a RegExp or useexpect.stringContaining("partial string").

Examples

X

Closing will discard any changes

Delete

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 atext 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.

toHaveSelection(expectedSelection?: string)

prev

text selected text

next

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, which was in turn extracted out of 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 and add it here!

If you would like to further test the accessibility and validity of the DOM consider 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.

This library follows the same guiding principles as its mother library DOM Testing Library. Go check them outfor 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):

Kent C. Dodds Kent C. Dodds๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ Ryan Castner Ryan Castner๐Ÿ“– Daniel Sandiego Daniel Sandiego๐Ÿ’ป Paweล‚ Mikoล‚ajczyk Paweล‚ Mikoล‚ajczyk๐Ÿ’ป Alejandro ร‘รกรฑez Ortiz Alejandro ร‘รกรฑez Ortiz๐Ÿ“– Matt Parrish Matt Parrish๐Ÿ› ๐Ÿ’ป ๐Ÿ“– โš ๏ธ Justin Hall Justin Hall๐Ÿ“ฆ
Anto Aravinth Anto Aravinth๐Ÿ’ป โš ๏ธ ๐Ÿ“– Jonah Moses Jonah Moses๐Ÿ“– ลukasz Gandecki ลukasz Gandecki๐Ÿ’ป โš ๏ธ ๐Ÿ“– Ivan Babak Ivan Babak๐Ÿ› ๐Ÿค” Jesse Day Jesse Day๐Ÿ’ป Ernesto Garcรญa Ernesto Garcรญa๐Ÿ’ป ๐Ÿ“– โš ๏ธ Mark Volkmann Mark Volkmann๐Ÿ› ๐Ÿ’ป
smacpherson64 smacpherson64๐Ÿ’ป ๐Ÿ“– โš ๏ธ John Gozde John Gozde๐Ÿ› ๐Ÿ’ป Iwona Iwona๐Ÿ’ป ๐Ÿ“– โš ๏ธ Lewis Lewis๐Ÿ’ป Leandro Lourenci Leandro Lourenci๐Ÿ› ๐Ÿ“– ๐Ÿ’ป โš ๏ธ Shukhrat Mukimov Shukhrat Mukimov๐Ÿ› Roman Usherenko Roman Usherenko๐Ÿ’ป โš ๏ธ
Joe Hsu Joe Hsu๐Ÿ“– Haz Haz๐Ÿ› ๐Ÿ’ป ๐Ÿค” Revath S Kumar Revath S Kumar๐Ÿ’ป hiwelo. hiwelo.๐Ÿ’ป ๐Ÿค” โš ๏ธ ลukasz Fiszer ลukasz Fiszer๐Ÿ’ป Jean Chung Jean Chung๐Ÿ’ป โš ๏ธ CarlaTeo CarlaTeo๐Ÿ’ป โš ๏ธ
Yarden Shoham Yarden Shoham๐Ÿ“– Jaga Santagostino Jaga Santagostino๐Ÿ› โš ๏ธ ๐Ÿ“– Connor Meredith Connor Meredith๐Ÿ’ป โš ๏ธ ๐Ÿ“– Pawel Wolak Pawel Wolakโš ๏ธ ๐Ÿ’ป Michaรซl De Boey Michaรซl De Boey๐Ÿš‡ Jฤnis Zarลพeckis Jฤnis Zarลพeckis๐Ÿ“– koala-lava koala-lava๐Ÿ“–
Juan Pablo Blanco Juan Pablo Blanco๐Ÿ“– Ben Monro Ben Monro๐Ÿ“– Jeff Bernstein Jeff Bernstein๐Ÿ“– Sergi Sergi๐Ÿ’ป โš ๏ธ Spencer Miskoviak Spencer Miskoviak๐Ÿ“– Jon Rimmer Jon Rimmer๐Ÿ’ป โš ๏ธ Luca Barone Luca Barone๐Ÿ’ป โš ๏ธ ๐Ÿค”
Malte Felmy Malte Felmy๐Ÿ’ป โš ๏ธ Championrunner Championrunner๐Ÿ“– Patrick Smith Patrick Smith๐Ÿ’ป โš ๏ธ ๐Ÿ“– Rubรฉn Moya Rubรฉn Moya๐Ÿ’ป โš ๏ธ ๐Ÿ“– Daniela Valero Daniela Valero๐Ÿ’ป โš ๏ธ ๐Ÿ“– Vladislav Katsura Vladislav Katsura๐Ÿ’ป โš ๏ธ Tim Fischbach Tim Fischbach๐Ÿ’ป โš ๏ธ ๐Ÿค”
Katie Boedges Katie Boedges๐Ÿš‡ Brian Alexis Brian Alexisโš ๏ธ Boris Serdiuk Boris Serdiuk๐Ÿ› ๐Ÿ’ป โš ๏ธ Dana Woodman Dana Woodman๐Ÿ“– Mo Sattler Mo Sattler๐Ÿ“– Geoff Rich Geoff Rich๐Ÿ’ป โš ๏ธ ๐Ÿค” ๐Ÿ› Syneva Syneva๐Ÿ’ป
Nick McCurdy Nick McCurdy๐Ÿ“– ๐Ÿ› ๐Ÿ’ป Obed Marquez Parlapiano Obed Marquez Parlapiano๐Ÿ“– Caleb Eby Caleb Eby๐Ÿ“– ๐Ÿ’ป โš ๏ธ Marcel Barner Marcel Barner๐Ÿ’ป โš ๏ธ Doma Doma๐Ÿ’ป โš ๏ธ Julien Wajsberg Julien Wajsberg๐Ÿ’ป โš ๏ธ steven nguyen steven nguyen๐Ÿ“–
tu4mo tu4mo๐Ÿ“– Matan Borenkraout Matan Borenkraout๐Ÿ“ฆ Yann Braga Yann Braga๐Ÿ’ป Ian VanSchooten Ian VanSchooten๐Ÿ’ป Chantal Broeren Chantal Broeren๐Ÿ“– Jรฉrรฉmie Astori Jรฉrรฉmie Astori๐Ÿ’ป ๐Ÿค” Ashley Ryan Ashley Ryan๐Ÿ’ป ๐Ÿค”
Fotis Papadogeorgopoulos Fotis Papadogeorgopoulos๐Ÿ’ป ๐Ÿ“– โš ๏ธ Jake Boone Jake Boone๐Ÿ’ป โš ๏ธ Stephan Kรถninger Stephan Kรถninger๐Ÿ› ๐Ÿ’ป Michael Manzinger Michael Manzinger๐Ÿ› ๐Ÿ’ป โš ๏ธ Dennis Chen Dennis Chen๐Ÿ’ป Tony Hallett Tony Hallett๐Ÿ› David DOLCIMASCOLO David DOLCIMASCOLO๐Ÿšง
Aleksandr Elkin Aleksandr Elkin๐Ÿšง Mordechai Dror Mordechai Dror๐Ÿ’ป Wayne Van Son Wayne Van Son๐Ÿ’ป โš ๏ธ Idan Entin Idan Entin๐Ÿ’ป โš ๏ธ mibcadet mibcadet๐Ÿ“– Silviu Alexandru Avram Silviu Alexandru Avram๐Ÿ’ป โš ๏ธ Gareth Jones Gareth Jones๐Ÿ’ป
Billy Janitsch Billy Janitsch๐Ÿ› InfiniteXyy InfiniteXyy๐Ÿ’ป ๐Ÿ›

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT