Gathering detailed insights and metrics for @testing-library/jest-dom
As of June 2024, the npm registry hosts over 2 million packages, making it one of the largest open-source software repositories in the world.
Gathering detailed insights and metrics for @testing-library/jest-dom
As of June 2024, the npm registry hosts over 2 million packages, making it one of the largest open-source software repositories in the world.
npm install @testing-library/jest-dom
98.2
Supply Chain
99.6
Quality
95.7
Maintenance
100
Vulnerability
99.6
License
4,446 Stars
275 Commits
401 Forks
32 Watching
6 Branches
129 Contributors
Updated on 22 Nov 2024
JavaScript (85.51%)
TypeScript (14.49%)
Cumulative downloads
Total Downloads
Last day
9.7%
489,214
Compared to previous day
Last week
9.4%
13,155,868
Compared to previous week
Last month
1.2%
52,231,571
Compared to previous month
Last year
35.5%
527,952,474
Compared to previous year
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.
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.
toBeDisabled
toBeEnabled
toBeEmptyDOMElement
toBeInTheDocument
toBeInvalid
toBeRequired
toBeValid
toBeVisible
toContainElement
toContainHTML
toHaveAccessibleDescription
toHaveAccessibleErrorMessage
toHaveAccessibleName
toHaveAttribute
toHaveClass
toHaveFocus
toHaveFormValues
toHaveStyle
toHaveTextContent
toHaveValue
toHaveDisplayValue
toBeChecked
toBePartiallyChecked
toHaveRole
toHaveErrorMessage
toHaveSelection
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 at eslint-plugin-jest-dom.
Import @testing-library/jest-dom
once (for instance in your tests setup
file) and you're good to go:
1// In your own jest-setup.js (or any other name) 2import '@testing-library/jest-dom' 3 4// In jest.config.js add (if you haven't already) 5setupFilesAfterEnv: ['<rootDir>/jest-setup.js']
@jest/globals
If you are using @jest/globals
with
injectGlobals: false
, you will need to use a different
import in your tests setup file:
1// In your own jest-setup.js (or any other name) 2import '@testing-library/jest-dom/jest-globals'
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:
1// In your own vitest-setup.js (or any other name) 2import '@testing-library/jest-dom/vitest' 3 4// In vitest.config.js add (if you haven't already) 5setupFiles: ['./vitest-setup.js']
Also, depending on your local setup, you may need to update your
tsconfig.json
:
1 // In tsconfig.json 2 "compilerOptions": { 3 ... 4 "types": ["vitest/globals", "@testing-library/jest-dom"] 5 }, 6 "include": [ 7 ... 8 "./vitest.setup.ts" 9 ],
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:
1 // In tsconfig.json 2 "include": [ 3 ... 4 "./jest-setup.ts" 5 ],
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:
1import * as matchers from '@testing-library/jest-dom/matchers' 2import {expect} from 'my-test-runner/expect' 3 4expect.extend(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
1toBeDisabled()
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:
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.
1<button data-testid="button" type="submit" disabled>submit</button> 2<fieldset disabled><input type="text" data-testid="input" /></fieldset> 3<a href="..." disabled>link</a>
1expect(getByTestId('button')).toBeDisabled() 2expect(getByTestId('input')).toBeDisabled() 3expect(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.
toBeEnabled
1toBeEnabled()
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.
toBeEmptyDOMElement
1toBeEmptyDOMElement()
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.
1<span data-testid="not-empty"><span data-testid="empty"></span></span> 2<span data-testid="with-whitespace"> </span> 3<span data-testid="with-comment"><!-- comment --></span>
1expect(getByTestId('empty')).toBeEmptyDOMElement() 2expect(getByTestId('not-empty')).not.toBeEmptyDOMElement() 3expect(getByTestId('with-whitespace')).not.toBeEmptyDOMElement()
toBeInTheDocument
1toBeInTheDocument()
This allows you to assert whether an element is present in the document or not.
1<span data-testid="html-element"><span>Html Element</span></span> 2<svg data-testid="svg-element"></svg>
1expect( 2 getByTestId(document.documentElement, 'html-element'), 3).toBeInTheDocument() 4expect(getByTestId(document.documentElement, 'svg-element')).toBeInTheDocument() 5expect( 6 queryByTestId(document.documentElement, 'does-not-exist'), 7).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
1toBeInvalid()
This allows you to check if an element, is currently invalid.
An element is invalid if it has an
aria-invalid
attribute
with no value or a value of "true"
, or if the result of
checkValidity()
is false
.
1<input data-testid="no-aria-invalid" /> 2<input data-testid="aria-invalid" aria-invalid /> 3<input data-testid="aria-invalid-value" aria-invalid="true" /> 4<input data-testid="aria-invalid-false" aria-invalid="false" /> 5 6<form data-testid="valid-form"> 7 <input /> 8</form> 9 10<form data-testid="invalid-form"> 11 <input required /> 12</form>
1expect(getByTestId('no-aria-invalid')).not.toBeInvalid() 2expect(getByTestId('aria-invalid')).toBeInvalid() 3expect(getByTestId('aria-invalid-value')).toBeInvalid() 4expect(getByTestId('aria-invalid-false')).not.toBeInvalid() 5 6expect(getByTestId('valid-form')).not.toBeInvalid() 7expect(getByTestId('invalid-form')).toBeInvalid()
toBeRequired
1toBeRequired()
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.
1<input data-testid="required-input" required /> 2<input data-testid="aria-required-input" aria-required="true" /> 3<input data-testid="conflicted-input" required aria-required="false" /> 4<input data-testid="aria-not-required-input" aria-required="false" /> 5<input data-testid="optional-input" /> 6<input data-testid="unsupported-type" type="image" required /> 7<select data-testid="select" required></select> 8<textarea data-testid="textarea" required></textarea> 9<div data-testid="supported-role" role="tree" required></div> 10<div data-testid="supported-role-aria" role="tree" aria-required="true"></div>
1expect(getByTestId('required-input')).toBeRequired() 2expect(getByTestId('aria-required-input')).toBeRequired() 3expect(getByTestId('conflicted-input')).toBeRequired() 4expect(getByTestId('aria-not-required-input')).not.toBeRequired() 5expect(getByTestId('optional-input')).not.toBeRequired() 6expect(getByTestId('unsupported-type')).not.toBeRequired() 7expect(getByTestId('select')).toBeRequired() 8expect(getByTestId('textarea')).toBeRequired() 9expect(getByTestId('supported-role')).not.toBeRequired() 10expect(getByTestId('supported-role-aria')).toBeRequired()
toBeValid
1toBeValid()
This allows you to check if the value of an element, is currently valid.
An element is valid if it has no
aria-invalid
attributes
or an attribute value of "false"
. The result of
checkValidity()
must also be true
if it's a form element.
1<input data-testid="no-aria-invalid" /> 2<input data-testid="aria-invalid" aria-invalid /> 3<input data-testid="aria-invalid-value" aria-invalid="true" /> 4<input data-testid="aria-invalid-false" aria-invalid="false" /> 5 6<form data-testid="valid-form"> 7 <input /> 8</form> 9 10<form data-testid="invalid-form"> 11 <input required /> 12</form>
1expect(getByTestId('no-aria-invalid')).toBeValid() 2expect(getByTestId('aria-invalid')).not.toBeValid() 3expect(getByTestId('aria-invalid-value')).not.toBeValid() 4expect(getByTestId('aria-invalid-false')).toBeValid() 5 6expect(getByTestId('valid-form')).toBeValid() 7expect(getByTestId('invalid-form')).not.toBeValid()
toBeVisible
1toBeVisible()
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:
display
set to none
visibility
set to either hidden
or
collapse
opacity
set to 0
hidden
attribute<details />
it has the open
attribute1<div data-testid="zero-opacity" style="opacity: 0">Zero Opacity Example</div> 2<div data-testid="visibility-hidden" style="visibility: hidden"> 3 Visibility Hidden Example 4</div> 5<div data-testid="display-none" style="display: none">Display None Example</div> 6<div style="opacity: 0"> 7 <span data-testid="hidden-parent">Hidden Parent Example</span> 8</div> 9<div data-testid="visible">Visible Example</div> 10<div data-testid="hidden-attribute" hidden>Hidden Attribute Example</div> 11<details> 12 <summary>Title of hidden text</summary> 13 Hidden Details Example 14</details> 15<details open> 16 <summary>Title of visible text</summary> 17 <div>Visible Details Example</div> 18</details>
1expect(getByText('Zero Opacity Example')).not.toBeVisible() 2expect(getByText('Visibility Hidden Example')).not.toBeVisible() 3expect(getByText('Display None Example')).not.toBeVisible() 4expect(getByText('Hidden Parent Example')).not.toBeVisible() 5expect(getByText('Visible Example')).toBeVisible() 6expect(getByText('Hidden Attribute Example')).not.toBeVisible() 7expect(getByText('Hidden Details Example')).not.toBeVisible() 8expect(getByText('Visible Details Example')).toBeVisible()
toContainElement
1toContainElement(element: HTMLElement | SVGElement | null)
This allows you to assert whether an element contains another element as a descendant or not.
1<span data-testid="ancestor"><span data-testid="descendant"></span></span>
1const ancestor = getByTestId('ancestor') 2const descendant = getByTestId('descendant') 3const nonExistantElement = getByTestId('does-not-exist') 4 5expect(ancestor).toContainElement(descendant) 6expect(descendant).not.toContainElement(ancestor) 7expect(ancestor).not.toContainElement(nonExistantElement)
toContainHTML
1toContainHTML(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.
1<span data-testid="parent"><span data-testid="child"></span></span>
1// These are valid uses 2expect(getByTestId('parent')).toContainHTML('<span data-testid="child"></span>') 3expect(getByTestId('parent')).toContainHTML('<span data-testid="child" />') 4expect(getByTestId('parent')).not.toContainHTML('<br />') 5 6// These won't work 7expect(getByTestId('parent')).toContainHTML('data-testid="child"') 8expect(getByTestId('parent')).toContainHTML('data-testid') 9expect(getByTestId('parent')).toContainHTML('</span>')
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
instead.
toHaveAccessibleDescription
1toHaveAccessibleDescription(expectedAccessibleDescription?: string | RegExp)
This allows you to assert that an element has the expected accessible 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 using expect.stringContaining/expect.stringMatching.
1<a 2 data-testid="link" 3 href="/" 4 aria-label="Home page" 5 title="A link to start over" 6 >Start</a 7> 8<a data-testid="extra-link" href="/about" aria-label="About page">About</a> 9<img src="avatar.jpg" data-testid="avatar" alt="User profile pic" /> 10<img 11 src="logo.jpg" 12 data-testid="logo" 13 alt="Company logo" 14 aria-describedby="t1" 15/> 16<span id="t1" role="presentation">The logo of Our Company</span> 17<img 18 src="logo.jpg" 19 data-testid="logo2" 20 alt="Company logo" 21 aria-description="The logo of Our Company" 22/>
1expect(getByTestId('link')).toHaveAccessibleDescription() 2expect(getByTestId('link')).toHaveAccessibleDescription('A link to start over') 3expect(getByTestId('link')).not.toHaveAccessibleDescription('Home page') 4expect(getByTestId('extra-link')).not.toHaveAccessibleDescription() 5expect(getByTestId('avatar')).not.toHaveAccessibleDescription() 6expect(getByTestId('logo')).not.toHaveAccessibleDescription('Company logo') 7expect(getByTestId('logo')).toHaveAccessibleDescription( 8 'The logo of Our Company', 9) 10expect(getByTestId('logo2')).toHaveAccessibleDescription( 11 'The logo of Our Company', 12)
toHaveAccessibleErrorMessage
1toHaveAccessibleErrorMessage(expectedAccessibleErrorMessage?: string | RegExp)
This allows you to assert that an element has the expected accessible 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 using expect.stringContaining/expect.stringMatching.
1<input 2 aria-label="Has Error" 3 aria-invalid="true" 4 aria-errormessage="error-message" 5/> 6<div id="error-message" role="alert">This field is invalid</div> 7 8<input aria-label="No Error Attributes" /> 9<input 10 aria-label="Not Invalid" 11 aria-invalid="false" 12 aria-errormessage="error-message" 13/>
1// Inputs with Valid Error Messages 2expect(getByRole('textbox', {name: 'Has Error'})).toHaveAccessibleErrorMessage() 3expect(getByRole('textbox', {name: 'Has Error'})).toHaveAccessibleErrorMessage( 4 'This field is invalid', 5) 6expect(getByRole('textbox', {name: 'Has Error'})).toHaveAccessibleErrorMessage( 7 /invalid/i, 8) 9expect( 10 getByRole('textbox', {name: 'Has Error'}), 11).not.toHaveAccessibleErrorMessage('This field is absolutely correct!') 12 13// Inputs without Valid Error Messages 14expect( 15 getByRole('textbox', {name: 'No Error Attributes'}), 16).not.toHaveAccessibleErrorMessage() 17 18expect( 19 getByRole('textbox', {name: 'Not Invalid'}), 20).not.toHaveAccessibleErrorMessage()
toHaveAccessibleName
1toHaveAccessibleName(expectedAccessibleName?: string | RegExp)
This allows you to assert that an element has the expected accessible 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 using expect.stringContaining/expect.stringMatching.
1<img data-testid="img-alt" src="" alt="Test alt" /> 2<img data-testid="img-empty-alt" src="" alt="" /> 3<svg data-testid="svg-title"><title>Test title</title></svg> 4<button data-testid="button-img-alt"><img src="" alt="Test" /></button> 5<p><img data-testid="img-paragraph" src="" alt="" /> Test content</p> 6<button data-testid="svg-button"><svg><title>Test</title></svg></p> 7<div><svg data-testid="svg-without-title"></svg></div> 8<input data-testid="input-title" title="test" />
1expect(getByTestId('img-alt')).toHaveAccessibleName('Test alt') 2expect(getByTestId('img-empty-alt')).not.toHaveAccessibleName() 3expect(getByTestId('svg-title')).toHaveAccessibleName('Test title') 4expect(getByTestId('button-img-alt')).toHaveAccessibleName() 5expect(getByTestId('img-paragraph')).not.toHaveAccessibleName() 6expect(getByTestId('svg-button')).toHaveAccessibleName() 7expect(getByTestId('svg-without-title')).not.toHaveAccessibleName() 8expect(getByTestId('input-title')).toHaveAccessibleName()
toHaveAttribute
1toHaveAttribute(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 using expect.stringContaining/expect.stringMatching
1<button data-testid="ok-button" type="submit" disabled>ok</button>
1const button = getByTestId('ok-button') 2 3expect(button).toHaveAttribute('disabled') 4expect(button).toHaveAttribute('type', 'submit') 5expect(button).not.toHaveAttribute('type', 'button') 6 7expect(button).toHaveAttribute('type', expect.stringContaining('sub')) 8expect(button).toHaveAttribute('type', expect.not.stringContaining('but'))
toHaveClass
1toHaveClass(...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.
1<button data-testid="delete-button" class="btn extra btn-danger"> 2 Delete item 3</button> 4<button data-testid="no-classes">No Classes</button>
1const deleteButton = getByTestId('delete-button') 2const noClasses = getByTestId('no-classes') 3 4expect(deleteButton).toHaveClass('extra') 5expect(deleteButton).toHaveClass('btn-danger btn') 6expect(deleteButton).toHaveClass(/danger/, 'btn') 7expect(deleteButton).toHaveClass('btn-danger', 'btn') 8expect(deleteButton).not.toHaveClass('btn-link') 9expect(deleteButton).not.toHaveClass(/link/) 10expect(deleteButton).not.toHaveClass(/btn extra/) // It does not match 11 12expect(deleteButton).toHaveClass('btn-danger extra btn', {exact: true}) // to check if the element has EXACTLY a set of classes 13expect(deleteButton).not.toHaveClass('btn-danger extra', {exact: true}) // if it has more than expected it is going to fail 14 15expect(noClasses).not.toHaveClass()
toHaveFocus
1toHaveFocus()
This allows you to assert whether an element has focus or not.
1<div><input type="text" data-testid="element-to-focus" /></div>
1const input = getByTestId('element-to-focus') 2 3input.focus() 4expect(input).toHaveFocus() 5 6input.blur() 7expect(input).not.toHaveFocus()
toHaveFormValues
1toHaveFormValues(expectedValues: { 2 [name: string]: any 3})
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 form or 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:
<input type="number">
elements return the value as a number, instead of
a string.<input type="checkbox">
elements:
name
attribute, it is treated as a
boolean, returning true
if the checkbox is checked, false
if
unchecked.name
attribute, they are
all treated collectively as a single form control, which returns the value
as an array containing all the values of the selected checkboxes in the
collection.<input type="radio">
elements are all grouped by the name
attribute, and
such a group treated as a single form control. This form control returns the
value as a string corresponding to the value
attribute of the selected
radio button within the group.<input type="text">
elements return the value as a string. This also
applies to <input>
elements having any other possible type
attribute
that's not explicitly covered in different rules above (e.g. search
,
email
, date
, password
, hidden
, etc.)<select>
elements without the multiple
attribute return the value as a
string corresponding to the value
attribute of the selected option
, or
undefined
if there's no selected option.<select multiple>
elements return the value as an array containing all
the values of the selected options.<textarea>
elements return their value as a string. The value
corresponds to their node content.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.
1<form data-testid="login-form"> 2 <input type="text" name="username" value="jane.doe" /> 3 <input type="password" name="password" value="12345678" /> 4 <input type="checkbox" name="rememberMe" checked /> 5 <button type="submit">Sign in</button> 6</form>
1expect(getByTestId('login-form')).toHaveFormValues({ 2 username: 'jane.doe', 3 rememberMe: true, 4})
toHaveStyle
1toHaveStyle(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.
1<button 2 data-testid="delete-button" 3 style="display: none; background-color: red" 4> 5 Delete item 6</button>
1const button = getByTestId('delete-button') 2 3expect(button).toHaveStyle('display: none') 4expect(button).toHaveStyle({display: 'none'}) 5expect(button).toHaveStyle(` 6 background-color: red; 7 display: none; 8`) 9expect(button).toHaveStyle({ 10 backgroundColor: 'red', 11 display: 'none', 12}) 13expect(button).not.toHaveStyle(` 14 background-color: blue; 15 display: none; 16`) 17expect(button).not.toHaveStyle({ 18 backgroundColor: 'blue', 19 display: 'none', 20})
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
1toHaveTextContent(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 /i
modifier.
If you want to match the whole content, you can use a RegExp
to do it.
1<span data-testid="text-content">Text Content</span>
1const element = getByTestId('text-content') 2 3expect(element).toHaveTextContent('Content') 4expect(element).toHaveTextContent(/^Text Content$/) // to match the whole content 5expect(element).toHaveTextContent(/content$/i) // to use case-insensitive match 6expect(element).not.toHaveTextContent('content')
toHaveValue
1toHaveValue(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
or
toHaveFormValues
.
It also accepts elements with roles meter
, progressbar
, slider
or
spinbutton
and checks their aria-valuenow
attribute (as a number).
For all other form elements, the value is matched using the same algorithm as in
toHaveFormValues
does.
1<input type="text" value="text" data-testid="input-text" /> 2<input type="number" value="5" data-testid="input-number" /> 3<input type="text" data-testid="input-empty" /> 4<select multiple data-testid="select-number"> 5 <option value="first">First Value</option> 6 <option value="second" selected>Second Value</option> 7 <option value="third" selected>Third Value</option> 8</select>
1const textInput = getByTestId('input-text') 2const numberInput = getByTestId('input-number') 3const emptyInput = getByTestId('input-empty') 4const selectInput = getByTestId('select-number') 5 6expect(textInput).toHaveValue('text') 7expect(numberInput).toHaveValue(5) 8expect(emptyInput).not.toHaveValue() 9expect(selectInput).toHaveValue(['second', 'third'])
toHaveDisplayValue
1toHaveDisplayValue(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
or
toHaveFormValues
.
1<label for="input-example">First name</label> 2<input type="text" id="input-example" value="Luca" /> 3 4<label for="textarea-example">Description</label> 5<textarea id="textarea-example">An example description here.</textarea> 6 7<label for="single-select-example">Fruit</label> 8<select id="single-select-example"> 9 <option value="">Select a fruit...</option> 10 <option value="banana">Banana</option> 11 <option value="ananas">Ananas</option> 12 <option value="avocado">Avocado</option> 13</select> 14 15<label for="multiple-select-example">Fruits</label> 16<select id="multiple-select-example" multiple> 17 <option value="">Select a fruit...</option> 18 <option value="banana" selected>Banana</option> 19 <option value="ananas">Ananas</option> 20 <option value="avocado" selected>Avocado</option> 21</select>
1const input = screen.getByLabelText('First name') 2const textarea = screen.getByLabelText('Description') 3const selectSingle = screen.getByLabelText('Fruit') 4const selectMultiple = screen.getByLabelText('Fruits') 5 6expect(input).toHaveDisplayValue('Luca') 7expect(input).toHaveDisplayValue(/Luc/) 8expect(textarea).toHaveDisplayValue('An example description here.') 9expect(textarea).toHaveDisplayValue(/example/) 10expect(selectSingle).toHaveDisplayValue('Select a fruit...') 11expect(selectSingle).toHaveDisplayValue(/Select/) 12expect(selectMultiple).toHaveDisplayValue([/Avocado/, 'Banana'])
toBeChecked
1toBeChecked()
This allows you to check whether the given element is checked. It accepts an
input
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"
.
1<input type="checkbox" checked data-testid="input-checkbox-checked" /> 2<input type="checkbox" data-testid="input-checkbox-unchecked" /> 3<div role="checkbox" aria-checked="true" data-testid="aria-checkbox-checked" /> 4<div 5 role="checkbox" 6 aria-checked="false" 7 data-testid="aria-checkbox-unchecked" 8/> 9 10<input type="radio" checked value="foo" data-testid="input-radio-checked" /> 11<input type="radio" value="foo" data-testid="input-radio-unchecked" /> 12<div role="radio" aria-checked="true" data-testid="aria-radio-checked" /> 13<div role="radio" aria-checked="false" data-testid="aria-radio-unchecked" /> 14<div role="switch" aria-checked="true" data-testid="aria-switch-checked" /> 15<div role="switch" aria-checked="false" data-testid="aria-switch-unchecked" />
1const inputCheckboxChecked = getByTestId('input-checkbox-checked') 2const inputCheckboxUnchecked = getByTestId('input-checkbox-unchecked') 3const ariaCheckboxChecked = getByTestId('aria-checkbox-checked') 4const ariaCheckboxUnchecked = getByTestId('aria-checkbox-unchecked') 5expect(inputCheckboxChecked).toBeChecked() 6expect(inputCheckboxUnchecked).not.toBeChecked() 7expect(ariaCheckboxChecked).toBeChecked() 8expect(ariaCheckboxUnchecked).not.toBeChecked() 9 10const inputRadioChecked = getByTestId('input-radio-checked') 11const inputRadioUnchecked = getByTestId('input-radio-unchecked') 12const ariaRadioChecked = getByTestId('aria-radio-checked') 13const ariaRadioUnchecked = getByTestId('aria-radio-unchecked') 14expect(inputRadioChecked).toBeChecked() 15expect(inputRadioUnchecked).not.toBeChecked() 16expect(ariaRadioChecked).toBeChecked() 17expect(ariaRadioUnchecked).not.toBeChecked() 18 19const ariaSwitchChecked = getByTestId('aria-switch-checked') 20const ariaSwitchUnchecked = getByTestId('aria-switch-unchecked') 21expect(ariaSwitchChecked).toBeChecked() 22expect(ariaSwitchUnchecked).not.toBeChecked()
toBePartiallyChecked
1toBePartiallyChecked()
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 checkbox
with a aria-checked="mixed"
, or input
of type checkbox
with
indeterminate
set to true
1<input type="checkbox" aria-checked="mixed" data-testid="aria-checkbox-mixed" /> 2<input type="checkbox" checked data-testid="input-checkbox-checked" /> 3<input type="checkbox" data-testid="input-checkbox-unchecked" /> 4<div role="checkbox" aria-checked="true" data-testid="aria-checkbox-checked" /> 5<div 6 role="checkbox" 7 aria-checked="false" 8 data-testid="aria-checkbox-unchecked" 9/> 10<input type="checkbox" data-testid="input-checkbox-indeterminate" />
1const ariaCheckboxMixed = getByTestId('aria-checkbox-mixed') 2const inputCheckboxChecked = getByTestId('input-checkbox-checked') 3const inputCheckboxUnchecked = getByTestId('input-checkbox-unchecked') 4const ariaCheckboxChecked = getByTestId('aria-checkbox-checked') 5const ariaCheckboxUnchecked = getByTestId('aria-checkbox-unchecked') 6const inputCheckboxIndeterminate = getByTestId('input-checkbox-indeterminate') 7 8expect(ariaCheckboxMixed).toBePartiallyChecked() 9expect(inputCheckboxChecked).not.toBePartiallyChecked() 10expect(inputCheckboxUnchecked).not.toBePartiallyChecked() 11expect(ariaCheckboxChecked).not.toBePartiallyChecked() 12expect(ariaCheckboxUnchecked).not.toBePartiallyChecked() 13 14inputCheckboxIndeterminate.indeterminate = true 15expect(inputCheckboxIndeterminate).toBePartiallyChecked()
toHaveRole
This allows you to assert that an element has the expected role.
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.
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'.
1toHaveRole(expectedRole: string)
1<button data-testid="button">Continue</button> 2<div role="button" data-testid="button-explicit">Continue</button> 3<button role="switch button" data-testid="button-explicit-multiple">Continue</button> 4<a href="/about" data-testid="link">About</a> 5<a data-testid="link-invalid">Invalid link<a/>
1expect(getByTestId('button')).toHaveRole('button') 2expect(getByTestId('button-explicit')).toHaveRole('button') 3expect(getByTestId('button-explicit-multiple')).toHaveRole('button') 4expect(getByTestId('button-explicit-multiple')).toHaveRole('switch') 5expect(getByTestId('link')).toHaveRole('link') 6expect(getByTestId('link-invalid')).not.toHaveRole('link') 7expect(getByTestId('link-invalid')).toHaveRole('generic')
toHaveErrorMessage
This custom matcher is deprecated. Prefer
toHaveAccessibleErrorMessage
instead, which is more comprehensive in implementing the official spec.
1toHaveErrorMessage(text: string | RegExp)
This allows you to check whether the given element has an ARIA 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 use
aria-invalid
in conjunction with aria-errormessage
. Learn more from
aria-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 /i
modifier.
To perform a partial match, you can pass a RegExp
or use
expect.stringContaining("partial string")
.
1<label for="startTime"> Please enter a start time for the meeting: </label> 2<input 3 id="startTime" 4 type="text" 5 aria-errormessage="msgID" 6 aria-invalid="true" 7 value="11:30 PM" 8/> 9<span id="msgID" aria-live="assertive" style="visibility:visible"> 10 Invalid time: the time must be between 9:00 AM and 5:00 PM 11</span>
1const timeInput = getByLabel('startTime') 2 3expect(timeInput).toHaveErrorMessage( 4 'Invalid time: the time must be between 9:00 AM and 5:00 PM', 5) 6expect(timeInput).toHaveErrorMessage(/invalid time/i) // to partially match 7expect(timeInput).toHaveErrorMessage(expect.stringContaining('Invalid time')) // to partially match 8expect(timeInput).not.toHaveErrorMessage('Pikachu!')
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 onlytoBeEmptyDOMElement
1toBeEmpty()
This allows you to assert whether an element has content or not.
1<span data-testid="not-empty"><span data-testid="empty"></span></span>
1expect(getByTestId('empty')).toBeEmpty() 2expect(getByTestId('not-empty')).not.toBeEmpty()
toBeInTheDOM
This custom matcher is deprecated. Prefer
toBeInTheDocument
instead.
1toBeInTheDOM()
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
or
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:
1expect(document.querySelector('.ok-button')).toBeInstanceOf(HTMLElement)
2expect(document.querySelector('.cancel-button')).toBeTruthy()
Note: The differences between
toBeInTheDOM
andtoBeInTheDocument
are significant. Replacing all uses oftoBeInTheDOM
withtoBeInTheDocument
will likely cause unintended consequences in your tests. Please make sure when replacingtoBeInTheDOM
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
instead, which is more comprehensive in implementing the official spec.
1toHaveDescription(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.
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.
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")
.
1<button aria-label="Close" aria-describedby="description-close">X</button> 2<div id="description-close">Closing will discard any changes</div> 3 4<button>Delete</button>
1const closeButton = getByRole('button', {name: 'Close'}) 2 3expect(closeButton).toHaveDescription('Closing will discard any changes') 4expect(closeButton).toHaveDescription(/will discard/) // to partially match 5expect(closeButton).toHaveDescription(expect.stringContaining('will discard')) // to partially match 6expect(closeButton).toHaveDescription(/^closing/i) // to use case-insensitive match 7expect(closeButton).not.toHaveDescription('Other description') 8 9const deleteButton = getByRole('button', {name: 'Delete'}) 10expect(deleteButton).not.toHaveDescription() 11expect(deleteButton).toHaveDescription('') // Missing or empty description always becomes a blank string
toHaveSelection
This allows to assert that an element has a text 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.
1toHaveSelection(expectedSelection?: string)
1<div> 2 <input type="text" value="text selected text" data-testid="text" /> 3 <textarea data-testid="textarea">text selected text</textarea> 4 <p data-testid="prev">prev</p> 5 <p data-testid="parent"> 6 text <span data-testid="child">selected</span> text 7 </p> 8 <p data-testid="next">next</p> 9</div>
1getByTestId('text').setSelectionRange(5, 13) 2expect(getByTestId('text')).toHaveSelection('selected') 3 4getByTestId('textarea').setSelectionRange(0, 5) 5expect('textarea').toHaveSelection('text ') 6 7const selection = document.getSelection() 8const range = document.createRange() 9selection.removeAllRanges() 10selection.empty() 11selection.addRange(range) 12 13// selection of child applies to the parent as well 14range.selectNodeContents(getByTestId('child')) 15expect(getByTestId('child')).toHaveSelection('selected') 16expect(getByTestId('parent')).toHaveSelection('selected') 17 18// selection that applies from prev all, parent text before child, and part child. 19range.setStart(getByTestId('prev'), 0) 20range.setEnd(getByTestId('child').childNodes[0], 3) 21expect(queryByTestId('prev')).toHaveSelection('prev') 22expect(queryByTestId('child')).toHaveSelection('sel') 23expect(queryByTestId('parent')).toHaveSelection('text sel') 24expect(queryByTestId('next')).not.toHaveSelection() 25 26// selection that applies from part child, parent text after child and part next. 27range.setStart(getByTestId('child').childNodes[0], 3) 28range.setEnd(getByTestId('next').childNodes[0], 2) 29expect(queryByTestId('child')).toHaveSelection('ected') 30expect(queryByTestId('parent')).toHaveSelection('ected text') 31expect(queryByTestId('prev')).not.toHaveSelection() 32expect(queryByTestId('next')).toHaveSelection('ne')
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.
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).
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 out 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.
Thanks goes to these people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
MIT
No vulnerabilities found.
Reason
15 commit(s) and 7 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 14/16 approved changesets -- score normalized to 8
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moreeslint-plugin-jest-dom
ESLint plugin to follow best practices and anticipate common mistakes when writing tests with jest-dom
testing-library-extra
Add bySelector and byAttribute to @testing-library/dom
@teamteanpm2024/nostrum-deleniti-fugit
[![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-im
@teamteanpm2024/dolores-beatae-possimus
![logo](https://user-images.githubusercontent.com/2213682/146607186-8e13ddef-26a4-4ebf-befd-5aac9d77c090.png)