🧪JEST
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
Usage
With TypeScript
Custom matchers
toBeDisabledtoBeEnabledtoBeEmptyDOMElementtoBeInTheDocumenttoBeInvalidtoBeRequiredtoBeValidtoBeVisibletoContainElementtoContainHTMLtoHaveAccessibleDescriptiontoHaveAccessibleNametoHaveAttributetoHaveClasstoHaveFocustoHaveFormValuestoHaveStyletoHaveTextContenttoHaveValuetoHaveDisplayValuetoBeCheckedtoBePartiallyCheckedtoHaveErrorMessage
Deprecated matchers
toBeEmptytoBeInTheDOMtoHaveDescription
Inspiration
Other Solutions
Guiding Principles
Contributors
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:
or
for installation with yarn package manager.
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.
Usage
Import @testing-library/jest-dom once (for instance in your tests setup file) and you're good to go:
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:
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
toBeDisabledThis 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.
Examples
This custom matcher does not take into account the presence or absence of the
aria-disabledattribute. For more on why this is the case, check #144.
toBeEnabled
toBeEnabledThis 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-disabledattribute. For more on why this is the case, check #144.
toBeEmptyDOMElement
toBeEmptyDOMElementThis 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
toBeInTheDocument
toBeInTheDocumentThis allows you to assert whether an element is present in the document or not.
Examples
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
toBeInvalidThis 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.
Examples
toBeRequired
toBeRequiredThis 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
toBeValid
toBeValidThis 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.
Examples
toBeVisible
toBeVisibleThis 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
displayset tononeit does not have its css property
visibilityset to eitherhiddenorcollapseit does not have its css property
opacityset to0its parent element is also visible (and so on up to the top of the DOM tree)
it does not have the
hiddenattributeif
<details />it has theopenattribute
Examples
toContainElement
toContainElementThis allows you to assert whether an element contains another element as a descendant or not.
Examples
toContainHTML
toContainHTMLAssert whether a string representing a HTML element is contained in another element. The string should contain valid html, and not any incomplete html.
Examples
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
toContainElementinstead.
toHaveAccessibleDescription
toHaveAccessibleDescriptionThis 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.
Examples
toHaveAccessibleName
toHaveAccessibleNameThis 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.
Examples
toHaveAttribute
toHaveAttributeThis 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
Examples
toHaveClass
toHaveClassThis 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.
Examples
toHaveFocus
toHaveFocusThis allows you to assert whether an element has focus or not.
Examples
toHaveFormValues
toHaveFormValuesThis 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
formandfieldsetto 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:if there's a single one with the given
nameattribute, it is treated as a boolean, returningtrueif the checkbox is checked,falseif unchecked.if there's more than one checkbox with the same
nameattribute, 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 thenameattribute, and such a group treated as a single form control. This form control returns the value as a string corresponding to thevalueattribute 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 possibletypeattribute that's not explicitly covered in different rules above (e.g.search,email,date,password,hidden, etc.)<select>elements without themultipleattribute return the value as a string corresponding to thevalueattribute of the selectedoption, orundefinedif 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.
Examples
toHaveStyle
toHaveStyleThis 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
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
toHaveTextContentThis 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.
Examples
toHaveValue
toHaveValueThis 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.
For all other form elements, the value is matched using the same algorithm as in toHaveFormValues does.
Examples
Using DOM Testing Library
toHaveDisplayValue
toHaveDisplayValueThis 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.
Examples
Using DOM Testing Library
toBeChecked
toBeCheckedThis 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".
Examples
toBePartiallyChecked
toBePartiallyCheckedThis 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
Examples
toHaveErrorMessage
toHaveErrorMessageThis 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").
Examples
Deprecated matchers
toBeEmpty
toBeEmptyNote: This matcher is being deprecated due to a name clash with
jest-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
toBeInTheDOM
toBeInTheDOMThis custom matcher is deprecated. Prefer
toBeInTheDocumentinstead.
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:
Note: The differences between
toBeInTheDOMandtoBeInTheDocumentare significant. Replacing all uses oftoBeInTheDOMwithtoBeInTheDocumentwill likely cause unintended consequences in your tests. Please make sure when replacingtoBeInTheDOMto read through the documentation of the proposed alternatives to see which use case works better for your needs.
toHaveDescription
toHaveDescriptionThis custom matcher is deprecated. Prefer
toHaveAccessibleDescriptioninstead, which is more comprehensive in implementing the official spec.
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").
Examples
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. 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.
Last updated
Was this helpful?
