Skip to content

πŸ¦‰ Custom jest matchers to test the dom structure

License

Notifications You must be signed in to change notification settings

jgoz/jest-dom

Β 
Β 

Repository files navigation

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 {toBeInTheDOM, toHaveClass} from 'jest-dom'

expect.extend({toBeInTheDOM, toHaveClass})

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

Custom matchers

toBeInTheDOM

toBeInTheDOM(container?: HTMLElement)

This allows you to assert whether an element present in the DOM container or not. If no DOM container is specified it will use the default DOM context.

Using the default DOM container

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <span data-testid="count-value">2</span>
expect(queryByTestId(container, 'count-value')).toBeInTheDOM()
expect(queryByTestId(container, 'count-value1')).not.toBeInTheDOM()
// ...

Using a specified DOM container

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <span data-testid="ancestor"><span data-testid="descendant"></span></span>
expect(queryByTestId(container, 'descendant')).toBeInTheDOM(
  queryByTestId(container, 'ancestor'),
)
expect(queryByTestId(container, 'ancestor')).not.toBeInTheDOM(
  queryByTestId(container, 'descendant'),
)
// ...

Note: when using toBeInTheDOM, make sure you use a query function (like queryByTestId) rather than a get function (like getByTestId). Otherwise the get* function could throw an error before your assertion.

toBeEmpty

toBeEmpty()

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

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <span data-testid="not-empty"><span data-testid="empty"></span></span>
expect(queryByTestId(container, 'empty')).toBeEmpty()
expect(queryByTestId(container, 'not-empty')).not.toBeEmpty()
// ...

toContainElement

toContainElement(element: HTMLElement)

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

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <span data-testid="ancestor"><span data-testid="descendant"></span></span>
const ancestor = queryByTestId(container, 'ancestor')
const descendant = queryByTestId(container, 'descendant')

expect(ancestor).toContainElement(descendant)
expect(descendant).not.toContainElement(ancestor)
// ...

toHaveTextContent

toHaveTextContent(text: string | RegExp)

This API allows you to check whether the given element has a text content or not.

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <span data-testid="count-value">2</span>
expect(getByTestId(container, 'count-value')).toHaveTextContent('2')
expect(getByTestId(container, 'count-value')).not.toHaveTextContent('21')
// ...

toHaveAttribute

toHaveAttribute(attr: string, value?: string)

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.

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <button data-testid="ok-button" type="submit" disabled>
//   OK
// </button>
expect(getByTestId(container, 'ok-button')).toHaveAttribute('disabled')
expect(getByTestId(container, 'ok-button')).toHaveAttribute('type', 'submit')
expect(getByTestId(container, 'ok-button')).not.toHaveAttribute(
  'type',
  'button',
)
// ...

toHaveClass

toHaveClass(...classNames: string[])

This allows you to check whether the given element has certain classes within its class attribute.

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <button data-testid="delete-button" class="btn extra btn-danger">
//   Delete item
// </button>
expect(getByTestId(container, 'delete-button')).toHaveClass('extra')
expect(getByTestId(container, 'delete-button')).toHaveClass('btn-danger btn')
expect(getByTestId(container, 'delete-button')).toHaveClass('btn-danger', 'btn')
expect(getByTestId(container, 'delete-button')).not.toHaveClass('btn-link')
// ...

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.

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <button data-testid="delete-button" style="display: none; color: red">
//   Delete item
// </button>
expect(getByTestId(container, 'delete-button')).toHaveStyle('display: none')
expect(getByTestId(container, 'delete-button')).toHaveStyle(`
  color: red;
  display: none;
`)
expect(getByTestId(container, 'delete-button')).not.toHaveStyle(`
  display: none;
  color: blue;
`)
// ...

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.

toHaveFocus

toHaveFocus()

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

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <div><input id="focused" type="text" data-testid="focused" /></div>
// const { container } = render(...)
// const input = container.querySelector('#focused');

// input.focus()
expect(queryByTestId(container, 'focused')).toHaveFocus()

// input.blur()
expect(queryByTestId(container, 'focused')).not.toHaveFocus()

// ...

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)
// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <header>
//   <h1 style="display: none">Page title</h1>
// </header>
// <section>
//   <p style="visibility: hidden">Hello <strong>World</strong></h1>
// </section>
expect(container.querySelector('header')).toBeVisible()
expect(container.querySelector('h1')).not.toBeVisible()
expect(container.querySelector('strong')).not.toBeVisible()
// ...

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.

// add the custom expect matchers once
import 'jest-dom/extend-expect'

// ...
// <button data-testid="button" type="submit" disabled>
//   SUBMIT
// </button>
// <fieldset disabled>
//   <input type="text" data-testid="text" />
// </fieldset>
expect(getByTestId(container, 'button')).toBeDisabled()
expect(getByTestId(container, 'text')).toBeDisabled()
// ...

// ...
// <a href="..." disabled>LINK</a>
expect(getByText(container, 'LINK')).not.toBeDisabled()
// ...

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

πŸ’» πŸ“– πŸš‡ ⚠️

Ryan Castner

πŸ“–

Daniel Sandiego

πŸ’»

PaweΕ‚ MikoΕ‚ajczyk

πŸ’»

Alejandro ÑÑñez Ortiz

πŸ“–

Matt Parrish

πŸ› πŸ’» πŸ“– ⚠️

Justin Hall

πŸ“¦

Anto Aravinth

πŸ’» ⚠️ πŸ“–

Jonah Moses

πŸ“–

Łukasz Gandecki

πŸ’» ⚠️ πŸ“–

Ivan Babak

πŸ› πŸ€”

Jesse Day

πŸ’»

Ernesto GarcΓ­a

πŸ’» πŸ“– ⚠️

Mark Volkmann

πŸ› πŸ’»

smacpherson64

πŸ’» πŸ“– ⚠️

John Gozde

πŸ› πŸ’»

Iwona

πŸ’» πŸ“– ⚠️

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

LICENSE

MIT

About

πŸ¦‰ Custom jest matchers to test the dom structure

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%