Skip to content
🦉 Custom jest matchers to test the state of the DOM
Branch: master
Clone or download

README.md

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

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 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 jest-dom

Usage

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

import 'jest-dom/extend-expect'

Alternatively, you can selectively import only the matchers you intend to use, and extend jest's expect yourself:

import {toBeInTheDocument, toHaveClass} from 'jest-dom'

expect.extend({toBeInTheDocument, toHaveClass})

Note: when using TypeScript, this way of importing matchers won't provide the necessary type definitions. More on this here.

Custom matchers

jest-dom can work with any library or framework that returns DOM elements from queries. The custom matcher examples below demonstrate using document.querySelector and dom-testing-library for querying DOM elements.

toBeDisabled

toBeDisabled()

This allows you to check whether an element is disabled from the user's perspective.

It matches if the element is a form control and the disabled attribute is specified on this element or the element is a descendant of a form element with a disabled attribute.

According to the specification, the following elements can be actually disabled: button, input, select, textarea, optgroup, option, fieldset.

Examples

<button data-testid="button" type="submit" disabled>submit</button>
<fieldset disabled><input type="text" data-testid="input" /></fieldset>
<a href="..." disabled>link</a>
Using document.querySelector
expect(document.querySelector('[data-testid="button"]')).toBeDisabled()
expect(document.querySelector('[data-testid="input"]')).toBeDisabled()
expect(document.querySelector('a')).not.toBeDisabled()
Using dom-testing-library
expect(getByTestId(container, 'button')).toBeDisabled()
expect(getByTestId(container, 'input')).toBeDisabled()
expect(getByText(container, 'link')).not.toBeDisabled()

toBeEnabled

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.


toBeEmpty

toBeEmpty()

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

Examples

<span data-testid="not-empty"><span data-testid="empty"></span></span>
Using document.querySelector
expect(document.querySelector('[data-testid="empty"]').toBeEmpty()
expect(document.querySelector('[data-testid="not-empty"]').not.toBeEmpty()
Using dom-testing-library
expect(queryByTestId(container, 'empty')).toBeEmpty()
expect(queryByTestId(container, 'not-empty')).not.toBeEmpty()

toBeInTheDocument

toBeInTheDocument()

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

Examples

<span data-testid="html-element"><span>Html Element</span></span>
<svg data-testid="svg-element"></svg>
Using document.querySelector
const htmlElement = document.querySelector('[data-testid="html-element"]')
const svgElement = document.querySelector('[data-testid="svg-element"]')
const nonExistantElement = document.querySelector('does-not-exist')
const detachedElement = document.createElement('div')

expect(htmlElement).toBeInTheDocument()
expect(svgElement).toBeInTheDocument()
expect(nonExistantElement).not.toBeInTheDocument()
expect(detachedElement).not.toBeInTheDocument()
Using dom-testing-library
expect(
  queryByTestId(document.documentElement, 'html-element'),
).toBeInTheDocument()
expect(
  queryByTestId(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

toBeInvalid()

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

An element is invalid if it is having an aria-invalid attribute or if the result of checkValidity() are false.

Examples

<input data-testid="no-aria-invalid" />
<input data-testid="aria-invalid" aria-invalid />
<input data-testid="aria-invalid-value" aria-invalid="true" />
<input data-testid="aria-invalid-false" aria-invalid="false" />
Using document.querySelector
expect(queryByTestId('no-aria-invalid')).not.toBeInvalid()
expect(queryByTestId('aria-invalid')).toBeInvalid()
expect(queryByTestId('aria-invalid-value')).toBeInvalid()
expect(queryByTestId('aria-invalid-false')).not.toBeInvalid()
Using dom-testing-library
expect(getByTestId(container, 'no-aria-invalid')).not.toBeInvalid()
expect(getByTestId(container, 'aria-invalid')).toBeInvalid()
expect(getByTestId(container, 'aria-invalid-value')).toBeInvalid()
expect(getByTestId(container, 'aria-invalid-false')).not.toBeInvalid()

toBeRequired

toBeRequired()

This allows you to check if an form element is currently required.

An element is required if it is having a required or aria-required="true" attribute.

Examples

<input data-testid="required-input" required />
<input data-testid="aria-required-input" aria-required="true" />
<input data-testid="conflicted-input" required aria-required="false" />
<input data-testid="aria-not-required-input" aria-required="false" />
<input data-testid="optional-input" />
<input data-testid="unsupported-type" type="image" required />
<select data-testid="select" required></select>
<textarea data-testid="textarea" required></textarea>
<div data-testid="supported-role" role="tree" required></div>
<div data-testid="supported-role-aria" role="tree" aria-required="true"></div>
Using document.querySelector
expect(document.querySelector('[data-testid="required-input"]')).toBeRequired()
expect(
  document.querySelector('[data-testid="aria-required-input"]'),
).toBeRequired()
expect(
  document.querySelector('[data-testid="conflicted-input"]'),
).toBeRequired()
expect(
  document.querySelector('[data-testid="aria-not-required-input"]'),
).not.toBeRequired()
expect(
  document.querySelector('[data-testid="unsupported-type"]'),
).not.toBeRequired()
expect(document.querySelector('[data-testid="select"]')).toBeRequired()
expect(document.querySelector('[data-testid="textarea"]')).toBeRequired()
expect(
  document.querySelector('[data-testid="supported-role"]'),
).not.toBeRequired()
expect(
  document.querySelector('[data-testid="supported-role-aria"]'),
).toBeRequired()
Using dom-testing-library
expect(getByTestId(container, 'required-input')).toBeRequired()
expect(getByTestId(container, 'aria-required-input')).toBeRequired()
expect(getByTestId(container, 'conflicted-input')).toBeRequired()
expect(getByTestId(container, 'aria-not-required-input')).not.toBeRequired()
expect(getByTestId(container, 'optional-input')).not.toBeRequired()
expect(getByTestId(container, 'unsupported-type')).not.toBeRequired()
expect(getByTestId(container, 'select')).toBeRequired()
expect(getByTestId(container, 'textarea')).toBeRequired()
expect(getByTestId(container, 'supported-role')).not.toBeRequired()
expect(getByTestId(container, 'supported-role-aria')).toBeRequired()

toBeValid

toBeValid()

This allows you to check if the value of a form element is currently valid.

An element is valid if it is not having an aria-invalid attribute or having false as a value and returning true when calling checkValidity().

Examples

<input data-testid="no-aria-invalid" />
<input data-testid="aria-invalid" aria-invalid />
<input data-testid="aria-invalid-value" aria-invalid="true" />
<input data-testid="aria-invalid-false" aria-invalid="false" />
Using document.querySelector
expect(queryByTestId('no-aria-invalid')).toBeValid()
expect(queryByTestId('aria-invalid')).not.toBeValid()
expect(queryByTestId('aria-invalid-value')).not.toBeValid()
expect(queryByTestId('aria-invalid-false')).toBeValid()
Using dom-testing-library
expect(getByTestId(container, 'no-aria-invalid')).toBeValid()
expect(getByTestId(container, 'aria-invalid')).not.toBeValid()
expect(getByTestId(container, 'aria-invalid-value')).not.toBeValid()
expect(getByTestId(container, 'aria-invalid-false')).toBeValid()

toBeVisible

toBeVisible()

This allows you to check if an element is currently visible to the user.

An element is visible if all the following conditions are met:

  • it does not have its css property display set to none
  • it does not have its css property visibility set to either hidden or collapse
  • it does not have its css property opacity set to 0
  • its parent element is also visible (and so on up to the top of the DOM tree)
  • it does not have the hidden attribute

Examples

<div data-testid="zero-opacity" style="opacity: 0">Zero Opacity Example</div>
<div data-testid="visibility-hidden" style="visibility: hidden">
  Visibility Hidden Example
</div>
<div data-testid="display-none" style="display: none">Display None Example</div>
<div style="opacity: 0">
  <span data-testid="hidden-parent">Hidden Parent Example</span>
</div>
<div data-testid="visible">Visible Example</div>
<div data-testid="hidden-attribute" hidden>Hidden Attribute Example</div>
Using document.querySelector
expect(document.querySelector('[data-testid="zero-opacity"]')).not.toBeVisible()
expect(
  document.querySelector('[data-testid="visibility-hidden"]'),
).not.toBeVisible()
expect(document.querySelector('[data-testid="display-none"]')).not.toBeVisible()
expect(
  document.querySelector('[data-testid="hidden-parent"]'),
).not.toBeVisible()
expect(document.querySelector('[data-testid="visible"]')).toBeVisible()
expect(
  document.querySelector('[data-testid="hidden-attribute"]'),
).not.toBeVisible()
Using dom-testing-library
expect(getByText(container, 'Zero Opacity Example')).not.toBeVisible()
expect(getByText(container, 'Visibility Hidden Example')).not.toBeVisible()
expect(getByText(container, 'Display None Example')).not.toBeVisible()
expect(getByText(container, 'Hidden Parent Example')).not.toBeVisible()
expect(getByText(container, 'Visible Example')).toBeVisible()
expect(getByText(container, 'Hidden Attribute Example')).not.toBeVisible()

toContainElement

toContainElement(element: HTMLElement | SVGElement | null)

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

Examples

<span data-testid="ancestor"><span data-testid="descendant"></span></span>
Using document.querySelector
const ancestor = document.querySelector('[data-testid="ancestor"]')
const descendant = document.querySelector('[data-testid="descendant"]')
const nonExistantElement = document.querySelector(
  '[data-testid="does-not-exist"]',
)

expect(ancestor).toContainElement(descendant)
expect(descendant).not.toContainElement(ancestor)
expect(ancestor).not.toContainElement(nonExistantElement)
Using dom-testing-library
const {queryByTestId} = render(/* Rendered HTML */)

const ancestor = queryByTestId(container, 'ancestor')
const descendant = queryByTestId(container, 'descendant')
const nonExistantElement = queryByTestId(container, '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:

Examples

<span data-testid="parent"><span data-testid="child"></span></span>
Using document.querySelector
expect(document.querySelector('[data-testid="parent"]')).toContainHTML(
  '<span data-testid="child"></span>',
)
Using dom-testing-library
expect(getByTestId(container, 'parent')).toContainHTML(
  '<span data-testid="child"></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.


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

Examples

<button data-testid="ok-button" type="submit" disabled>ok</button>
Using document.querySelector
const button = document.querySelector('[data-testid="ok-button"]')

expect(button).toHaveAttribute('disabled')
expect(button).toHaveAttribute('type', 'submit')
expect(button).not.toHaveAttribute('type', 'button')
Using dom-testing-library
const button = getByTestId(container, '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[])

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.

Examples

<button data-testid="delete-button" class="btn extra btn-danger">
  Delete item
</button>
<button data-testid="no-classes">No Classes</button>
Using document.querySelector
const deleteButton = document.querySelector('[data-testid="delete-button"]')
const noClasses = document.querySelector('[data-testid="no-classes"]')

expect(deleteButton).toHaveClass('extra')
expect(deleteButton).toHaveClass('btn-danger btn')
expect(deleteButton).toHaveClass('btn-danger', 'btn')
expect(deleteButton).not.toHaveClass('btn-link')

expect(noClasses).not.toHaveClass()
Using dom-testing-library
const deleteButton = getByTestId(container, 'delete-button')
const noClasses = getByTestId(container, 'no-classes')

expect(deleteButton).toHaveClass('extra')
expect(deleteButton).toHaveClass('btn-danger btn')
expect(deleteButton).toHaveClass('btn-danger', 'btn')
expect(deleteButton).not.toHaveClass('btn-link')

expect(noClasses).not.toHaveClass()

toHaveFocus

toHaveFocus()

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

Examples

<div><input type="text" data-testid="element-to-focus" /></div>
Using document.querySelector
const input = document.querySelector(['data-testid="element-to-focus"'])

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

input.blur()
expect(input).not.toHaveFocus()
Using dom-testing-library
const input = queryByTestId(container, 'element-to-focus')

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

fireEvent.blur(input)
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 form or a fieldset element.

This allows it to take advantage of the .elements property in form and fieldset 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:
    • if there's a single one with the given name attribute, it is treated as a boolean, returning true if the checkbox is checked, false if unchecked.
    • if there's more than one checkbox with the same 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.

Examples

<form data-testid="login-form">
  <input type="text" name="username" value="jane.doe" />
  <input type="password" name="password" value="12345678" />
  <input type="checkbox" name="rememberMe" checked />
  <button type="submit">Sign in</button>
</form>
const form = document.querySelector('[data-testid="login-form"]')
expect(form).toHaveFormValues({
  username: 'jane.doe',
  rememberMe: true,
})

toHaveStyle

toHaveStyle(css: string)

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; color: red">
  Delete item
</button>
Using document.querySelector
const button = document.querySelector(['data-testid="delete-button"')

expect(button).toHaveStyle('display: none')
expect(button).toHaveStyle(`
  color: red;
  display: none;
`)
expect(button).not.toHaveStyle(`
  color: blue;
  display: none;
`)
Using dom-testing-library
const button = getByTestId(container, 'delete-button')

expect(button).toHaveStyle('display: none')
expect(button).toHaveStyle(`
  color: red;
  display: none;
`)
expect(button).not.toHaveStyle(`
  color: 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 element has a text content or not.

When a string argument is passed through, it will perform a partial case-sensitive match to the element 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

<span data-testid="text-content">Text Content</span>
Using document.querySelector
const element = document.querySelector('[data-testid="text-content"]')

expect(element).toHaveTextContent('Content')
expect(element).toHaveTextContent(/^Text Content$/) // to match the whole content
expect(element).toHaveTextContent(/content$/i) // to use case-insentive match
expect(element).not.toHaveTextContent('content')
Using dom-testing-library
const element = getByTestId(container, 'text-content')

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

Deprecated matchers

toBeInTheDOM

toBeInTheDOM()

This allows you to check whether a value is a DOM element, or not.

Contrary to what its name implies, this matcher only checks that you passed to it a valid DOM element. It does not have a clear definition of that "the DOM" is. Therefore, it does not check wether 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:

expect(document.querySelector('.ok-button')).toBeInstanceOf(HTMLElement)
expect(document.querySelector('.cancel-button')).toBeTruthy()

Note: The differences between toBeInTheDOM and toBeInTheDocument are significant. Replacing all uses of toBeInTheDOM with toBeInTheDocument will likely cause unintended consequences in your tests. Please make sure when replacing toBeInTheDOM to read through the documentation of the proposed alternatives to see which use case works better for your needs.

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!

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

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.

💻 🤔 ⚠️

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

LICENSE

MIT

You can’t perform that action at this time.