Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/testing-library/jasmine-dom

🦥 Custom Jasmine matchers to test the state of the DOM
https://github.com/testing-library/jasmine-dom

testing

Last synced: 1 day ago
JSON representation

🦥 Custom Jasmine matchers to test the state of the DOM

Awesome Lists containing this project

README

        


jasmine-dom


sloth

Custom Jasmine matchers to test the state of the DOM

---

[![Build Status][build-badge]][build]
[![Code Coverage][coverage-badge]][coverage]
[![semantic-release][semantic-release-badge]][semantic-release]
[![version][version-badge]][package]
[![downloads][downloads-badge]][npmtrends]
[![MIT License][license-badge]][license]

[![All Contributors](https://img.shields.io/badge/all_contributors-7-orange.svg?style=flat-square)](#contributors-)

[![PRs Welcome][prs-badge]][prs]
[![Code of Conduct][coc-badge]][coc]
[![Discord][discord-badge]][discord]

[![Watch on GitHub][github-watch-badge]][github-watch]
[![Star on GitHub][github-star-badge]][github-star]
[![Tweet][twitter-badge]][twitter]

## The problem

You want to use [Jasmine][jasmine] to write tests that assert various things about the state of the 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 `jasmine-dom` library provides a set of custom Jasmine matchers that you can use to extend Jasmine. These will make your tests more declarative, clear to read and to maintain.

## Table of Contents

- [Installation](#installation)
- [Usage](#usage)
- [Custom matchers](#custom-matchers)
- [`toBeDisabled`](#tobedisabled)
- [`toBeEnabled`](#tobeenabled)
- [`toBeEmptyDOMElement`](#tobeemptydomelement)
- [`toBeInTheDocument`](#tobeinthedocument)
- [`toBeInvalid`](#tobeinvalid)
- [`toBeRequired`](#toberequired)
- [`toBeValid`](#tobevalid)
- [`toBeVisible`](#tobevisible)
- [`toContainHTML`](#tocontainhtml)
- [`toContainElement`](#tocontainelement)
- [`toHaveAccessibleDescription`](#tohaveaccessibledescription)
- [`toHaveAccessibleName`](#tohaveaccessiblename)
- [`toHaveAttribute`](#tohaveattribute)
- [`toHaveClassName`](#tohaveclassname)
- [`toHaveFocus`](#tohavefocus)
- [`toHaveFormValues`](#tohaveformvalues)
- [`toHaveStyle`](#tohavestyle)
- [`toHaveTextContent`](#tohavetextcontent)
- [`toHaveValue`](#tohavevalue)
- [`toHaveDisplayValue`](#tohavedisplayvalue)
- [`toBeChecked`](#tobechecked)
- [`toBePartiallyChecked`](#tobepartiallychecked)
- [`toHaveErrorMessage`](#tohaveerrormessage)
- [`toHaveDescription`](#tohavedescription)
- [Inspiration](#inspiration)
- [Other Solutions](#other-solutions)
- [Guiding Principles](#guiding-principles)
- [Contributors](#contributors)
- [LICENSE](#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`.

Using npm:

```
npm install --save-dev @testing-library/jasmine-dom
```

or for installation using [yarn][yarn] package manager:

```
yarn add --dev @testing-library/jasmine-dom
```

## Usage

### With JavaScript

You should have a directory for helpers specified inside the `/helpers` array in your `jasmine.json` file, for example:

```json
{
"spec_dir": "src/__tests__",
"spec_files": ["**/*.test.js"],
"helpers": ["helpers/**/*.js"],
"stopSpecOnExpectationFailure": false,
"random": false
}
```

Make a new file inside that directory, import `@testing-library/jasmine-dom` and add the matchers like so:

```javascript
import JasmineDOM from '@testing-library/jasmine-dom';

beforeAll(() => {
jasmine.addMatchers(JasmineDOM);
});
```

### With TypeScript

Install the type definitions with:

```
npm install --save-dev @types/testing-library__jasmine-dom
```

Add `"@testing-library/jasmine-dom"` to `/compilerOptions/types` in the tests `tsconfig`, for example:

```json
{
"compilerOptions": {
"types": ["jasmine", "node", "@testing-library/jasmine-dom"]
}
}
```

Follow the [JavaScript instructions](#with-javascript) to add the matchers.

### With Angular

Follow the [TypeScript instructions](#with-typescript) to install the type definitions, making sure to include the types in `tsconfig.spec.json`, the configuration file used for the test environment.

Add the matchers in the test setup file, which is typically located in `src/test.ts`:

```ts
import { getTestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import JasmineDOM from '@testing-library/jasmine-dom';

beforeAll(() => {
jasmine.addMatchers(JasmineDOM);
});

getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), {});
```

If your project was created with Angular 15 or later, you will not have a test setup file, so you will need to create one. Create a `test.ts` file in `src` with the code shown in the previous step, and then add the path to it in `angular.json` in `/projects//architect/test/options/main`:

```json
{
"projects": {
"myProject": {
"architect": {
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": ["zone.js", "zone.js/testing"],
"tsConfig": "tsconfig.spec.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"main": "src/test.ts",
"styles": ["src/styles.css"],
"scripts": []
}
}
}
}
}
}
```

## Matchers

This library is meant to be a Jasmine version of `@testing-library/jest-dom` library. As such, it provides the same set of matchers and the same functionality for each one, with a couple of minor diferences:

- `toBeEmpty()` is not included, in favor of `toBeEmptyDOMElement()`
- `toBeInTheDOM()` is not included, since it's deprecated
- `toHaveClass()` is renamed as `toHaveClassName()` to prevent name collision with Jasmine's `toHaveClass()`

### `toBeDisabled`

```typescript
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](https://html.spec.whatwg.org/multipage/semantics-other.html#disabled-elements):
`button`, `input`, `select`, `textarea`, `optgroup`, `option`, `fieldset`.

#### Examples

```html
submit

link
```

```javascript
expect(getByTestId('button')).toBeDisabled();
expect(getByTestId('input')).toBeDisabled();
expect(getByText('link')).not.toBeDisabled();
```


### `toBeEnabled`

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


### `toBeEmptyDOMElement`

```typescript
toBeEmptyDOMElement();
```

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

#### Examples

```html

```

```javascript
expect(getByTestId('empty')).toBeEmptyDOMElement();
expect(getByTestId('not-empty')).not.toBeEmptyDOMElement();
```


### `toBeInTheDocument`

```typescript
toBeInTheDocument();
```

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

#### Examples

```html
Html Element
```

```javascript
expect(getByTestId(document.documentElement, 'html-element')).toBeInTheDocument();
expect(getByTestId(document.documentElement, 'svg-element')).toBeInTheDocument();
expect(queryByTestId(document.documentElement, 'does-not-exist')).not.toBeInTheDocument();
```

> Note: This matcher does not find detached elements. The element must be added
> to the document to be found by toBeInTheDocument. If you desire to search in a
> detached element please use: [`toContainElement`](#tocontainelement)


### `toBeInvalid`

```typescript
toBeInvalid();
```

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

An element is invalid if it has an
[`aria-invalid` attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute)
with no value or a value of `"true"`, or if the result of
[`checkValidity()`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation)
is `false`.

#### Examples

```html

```

```javascript
expect(getByTestId('no-aria-invalid')).not.toBeInvalid();
expect(getByTestId('aria-invalid')).toBeInvalid();
expect(getByTestId('aria-invalid-value')).toBeInvalid();
expect(getByTestId('aria-invalid-false')).not.toBeInvalid();

expect(getByTestId('valid-form')).not.toBeInvalid();
expect(getByTestId('invalid-form')).toBeInvalid();
```


### `toBeRequired`

```typescript
toBeRequired();
```

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

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

#### Examples

```html



```

```javascript
expect(getByTestId('required-input')).toBeRequired();
expect(getByTestId('aria-required-input')).toBeRequired();
expect(getByTestId('conflicted-input')).toBeRequired();
expect(getByTestId('aria-not-required-input')).not.toBeRequired();
expect(getByTestId('optional-input')).not.toBeRequired();
expect(getByTestId('unsupported-type')).not.toBeRequired();
expect(getByTestId('select')).toBeRequired();
expect(getByTestId('textarea')).toBeRequired();
expect(getByTestId('supported-role')).not.toBeRequired();
expect(getByTestId('supported-role-aria')).toBeRequired();
```


### `toBeValid`

```typescript
toBeValid();
```

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

An element is valid if it has no
[`aria-invalid` attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute)s
or an attribute value of `"false"`. The result of
[`checkValidity()`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation)
must also be `true` if it's a form element.

#### Examples

```html

```

```javascript
expect(getByTestId('no-aria-invalid')).toBeValid();
expect(getByTestId('aria-invalid')).not.toBeValid();
expect(getByTestId('aria-invalid-value')).not.toBeValid();
expect(getByTestId('aria-invalid-false')).toBeValid();

expect(getByTestId('valid-form')).toBeValid();
expect(getByTestId('invalid-form')).not.toBeValid();
```


### `toBeVisible`

```typescript
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`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden)
attribute
- if `` it has the `open` attribute

#### Examples

```html

Zero Opacity Example

Visibility Hidden Example

Display None Example


Hidden Parent Example

Visible Example

Hidden Attribute Example

```

```javascript
expect(getByText('Zero Opacity Example')).not.toBeVisible();
expect(getByText('Visibility Hidden Example')).not.toBeVisible();
expect(getByText('Display None Example')).not.toBeVisible();
expect(getByText('Hidden Parent Example')).not.toBeVisible();
expect(getByText('Visible Example')).toBeVisible();
expect(getByText('Hidden Attribute Example')).not.toBeVisible();
```


### `toContainHTML`

```typescript
toContainHTML(htmlText: string)
```

Assert whether a string representing a HTML element is contained in another
element. The string should contain valid html, and not any incomplete html.

#### Examples

```html

```

```javascript
// These are valid uses
expect(getByTestId('parent')).toContainHTML('');
expect(getByTestId('parent')).toContainHTML('');
expect(getByTestId('parent')).not.toContainHTML('
');

// These won't work
expect(getByTestId('parent')).toContainHTML('data-testid="child"');
expect(getByTestId('parent')).toContainHTML('data-testid');
expect(getByTestId('parent')).toContainHTML('');
```

> Chances are you probably do not need to use this matcher. We encourage testing
> from the perspective of how the user perceives the app in a browser. That's
> why testing against a specific DOM structure is not advised.
>
> It could be useful in situations where the code being tested renders html that
> was obtained from an external source, and you want to validate that that html
> code was used as intended.
>
> It should not be used to check DOM structure that you control. Please use
> [`toContainElement`](#tocontainelement) instead.


### `toContainElement`

```typescript
toContainElement(element: HTMLElement | SVGElement | null)
```

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

#### Examples

```html

```

```javascript
const ancestor = getByTestId('ancestor');
const descendant = getByTestId('descendant');
const nonExistantElement = getByTestId('does-not-exist');

expect(ancestor).toContainElement(descendant);
expect(descendant).not.toContainElement(ancestor);
expect(ancestor).not.toContainElement(nonExistantElement);
```


### `toHaveAccessibleDescription`

```typescript
toHaveAccessibleDescription(expectedAccessibleDescription?: string | RegExp)
```

This allows you to assert that an element has the expected
[accessible description](https://w3c.github.io/accname/).

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
[jasmine.stringContaining](https://jasmine.github.io/api/edge/jasmine#.stringContaining)/[jasmine.stringMatching](https://jasmine.github.io/api/edge/jasmine#.stringMatching).

#### Examples

```html
Start
About
User profile pic
Company logo
The logo of Our Company
```

```js
expect(getByTestId('link')).toHaveAccessibleDescription();
expect(getByTestId('link')).toHaveAccessibleDescription('A link to start over');
expect(getByTestId('link')).not.toHaveAccessibleDescription('Home page');
expect(getByTestId('extra-link')).not.toHaveAccessibleDescription();
expect(getByTestId('avatar')).not.toHaveAccessibleDescription();
expect(getByTestId('logo')).not.toHaveAccessibleDescription('Company logo');
expect(getByTestId('logo')).toHaveAccessibleDescription('The logo of Our Company');
```


### `toHaveAccessibleName`

```typescript
toHaveAccessibleName(expectedAccessibleName?: string | RegExp)
```

This allows you to assert that an element has the expected
[accessible name](https://w3c.github.io/accname/). 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
[jasmine.stringContaining](https://jasmine.github.io/api/edge/jasmine#.stringContaining)/[jasmine.stringMatching](https://jasmine.github.io/api/edge/jasmine#.stringMatching).

#### Examples

```html
Test alt

Test title
Test

Test content


Test

```

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


### `toHaveAttribute`

```typescript
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 a RegExp.

#### Examples

```html
ok
```

```javascript
const button = getByTestId('ok-button')

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

expect(button).toHaveAttribute('type', /sub/))
expect(button).toHaveAttribute('type', /but/))
```


### `toHaveClassName`

```typescript
toHaveClassName(...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.

#### Examples

```html
Delete item
No Classes
```

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

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

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

expect(noClasses).not.toHaveClassName();
```


### `toHaveFocus`

```typescript
toHaveFocus();
```

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

#### Examples

```html


```

```javascript
const input = getByTestId('element-to-focus');

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

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


### `toHaveFormValues`

```typescript
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, ``
elements have a `value` attribute, but `` elements do not. Here's a list
of all cases covered:

- `` elements return the value as a **number**, instead of
a string.
- `` 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.
- `` 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.
- `` elements return the value as a **string**. This also
applies to `` elements having any other possible `type` attribute
that's not explicitly covered in different rules above (e.g. `search`,
`email`, `date`, `password`, `hidden`, etc.)
- `` 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.
- `` elements return the value as an **array** containing all
the values of the [selected options][].
- `` 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.

[selected options]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions
[form]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
[fieldset]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement
[.elements]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements

#### Examples

```html




Sign in

```

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

### `toHaveStyle`

```typescript
toHaveStyle(css: string | object)
```

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

#### Examples

```html
Delete item
```

```javascript
const button = getByTestId('delete-button');

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

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


### `toHaveTextContent`

```typescript
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

```html
Text Content
```

```javascript
const element = getByTestId('text-content');

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


### `toHaveValue`

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

This allows you to check whether the given form element has the specified value.
It accepts ``, `` and `` elements with the exception of
`` and ``, which can be meaningfully
matched only using [`toBeChecked`](#tobechecked) or
[`toHaveFormValues`](#tohaveformvalues).

For all other form elements, the value is matched using the same algorithm as in
[`toHaveFormValues`](#tohaveformvalues) does.

#### Examples

```html

First Value
Second Value
Third Value

```

##### Using DOM Testing Library

```javascript
const textInput = screen.getByTestId('input-text');
const numberInput = screen.getByTestId('input-number');
const emptyInput = screen.getByTestId('input-empty');
const selectInput = screen.getByTestId('select-number');

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


### `toHaveDisplayValue`

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

This allows you to check whether the given form element has the specified
displayed value (the one the end user will see). It accepts ``,
`` and `` elements with the exception of
`` and ``, which can be meaningfully
matched only using [`toBeChecked`](#tobechecked) or
[`toHaveFormValues`](#tohaveformvalues).

#### Examples

```html
First name

Description
An example description here.

Fruit

Select a fruit...
Banana
Ananas
Avocado

Fruits

Select a fruit...
Banana
Ananas
Avocado

```

##### Using DOM Testing Library

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

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


### `toBeChecked`

```typescript
toBeChecked();
```

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

#### Examples

```html






```

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

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

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


### `toBePartiallyChecked`

```typescript
toBePartiallyChecked();
```

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

#### Examples

```html


```

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

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

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


### `toHaveErrorMessage`

```typescript
toHaveErrorMessage(text: string | RegExp)
```

This allows you to check whether the given element has an
[ARIA error message](https://www.w3.org/TR/wai-aria/#aria-errormessage) 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](https://www.w3.org/TR/wai-aria/#aria-errormessage).

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
`jasmine.stringContaining("partial string")`.

#### Examples

```html
Please enter a start time for the meeting:


Invalid time: the time must be between 9:00 AM and 5:00 PM

```

```javascript
const timeInput = getByLabel('startTime');

expect(timeInput).toHaveErrorMessage('Invalid time: the time must be between 9:00 AM and 5:00 PM');
expect(timeInput).toHaveErrorMessage(/invalid time/i); // to partially match
expect(timeInput).toHaveErrorMessage(jasmine.stringContaining('Invalid time')); // to partially match
expect(timeInput).not.toHaveErrorMessage('Pikachu!');
```


### `toHaveDescription`

```typescript
toHaveDescription(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](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_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](https://www.w3.org/TR/accname-1.1/#mapping_additional_nd_description).

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

#### Examples

```html
X

Closing will discard any changes

Delete
```

```javascript
const closeButton = getByRole('button', { name: 'Close' });

expect(closeButton).toHaveDescription('Closing will discard any changes');
expect(closeButton).toHaveDescription(/will discard/); // to partially match
expect(closeButton).toHaveDescription(/^closing/i); // to use case-insensitive match
expect(closeButton).not.toHaveDescription('Other description');

const deleteButton = getByRole('button', { name: 'Delete' });
expect(deleteButton).not.toHaveDescription();
expect(deleteButton).toHaveDescription(''); // Missing or empty description always becomes a blank string
```

## Inspiration

This library was heavily inspired by [testing-library][testing-library] being [jest-dom][jest-dom] a part of its ecosystem, and [Kent C. Dodds'][kentcdodds] guiding principles.

The intention is to make these matchers available to developers using Jasmine instead of Jest.

## Other Solutions

I'm not aware of any, if you are please do make a PR and add it here!

For extending Jasmine's matchers outside the realm of DOM testing, [Jasmine-Matchers](https://github.com/JamieMason/Jasmine-Matchers) is an option.

## Guiding Principles

> [The more your tests resemble the way your software is used, the more confidence they can give you][guiding-principle]

## Contributors

Thanks goes to these people ([emoji key][emojis])



Kent C. Dodds
Kent C. Dodds

🚇
Brian Alexis
Brian Alexis

🤔 💻 📖 ⚠️
IanGrainger
IanGrainger

💻
Michaël De Boey
Michaël De Boey

🚇
Nick McCurdy
Nick McCurdy

🚇
Ori Livni
Ori Livni

💻 ⚠️
Sebastián Altamirano
Sebastián Altamirano

📖

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

## LICENSE

MIT

[jasmine]: https://jasmine.github.io/
[jest-dom]: https://testing-library.com/docs/ecosystem-jest-dom
[kentcdodds]: https://kentcdodds.com/
[npm]: https://www.npmjs.com/
[node]: https://nodejs.org
[testing-library]: https://testing-library.com/
[yarn]: https://yarnpkg.com

[build-badge]: https://img.shields.io/github/workflow/status/testing-library/jasmine-dom/validate?logo=github&style=flat-square
[build]: https://github.com/testing-library/jasmine-dom/actions?query=workflow%3Avalidate
[coverage-badge]: https://codecov.io/gh/testing-library/jasmine-dom/branch/main/graph/badge.svg
[coverage]: https://codecov.io/gh/testing-library/jasmine-dom
[version-badge]: https://img.shields.io/npm/v/@testing-library/jasmine-dom?style=flat-square
[semantic-release-badge]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
[semantic-release]: https://github.com/semantic-release/semantic-release
[package]: https://www.npmjs.com/package/@testing-library/jasmine-dom
[downloads-badge]: https://img.shields.io/npm/dm/@testing-library/jasmine-dom?style=flat-square
[npmtrends]: http://www.npmtrends.com/@testing-library/jasmine-dom
[license-badge]: https://img.shields.io/npm/l/@testing-library/jasmine-dom?style=flat-square
[license]: https://github.com/testing-library/jasmine-dom/blob/main/LICENSE
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: http://makeapullrequest.com
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
[coc]: https://github.com/testing-library/jasmine-dom/blob/main/other/CODE_OF_CONDUCT.md
[github-watch-badge]: https://img.shields.io/github/watchers/testing-library/jasmine-dom?style=social
[github-watch]: https://github.com/testing-library/jasmine-dom/watchers
[github-star-badge]: https://img.shields.io/github/stars/testing-library/jasmine-dom?style=social
[github-star]: https://github.com/testing-library/jasmine-dom/stargazers
[twitter]: https://twitter.com/intent/tweet?text=Check%20out%20jasmine-dom%20by%20%40brrianalexis%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fjasmine-dom%20%F0%9F%91%8D
[twitter-badge]: https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Ftesting-library%2Fjasmine-dom
[emojis]: https://allcontributors.org/docs/en/emoji-key
[all-contributors]: https://github.com/all-contributors/all-contributors
[all-contributors-badge]: https://img.shields.io/badge/all_contributors-5-orange.svg?style=flat-square
[guiding-principle]: https://testing-library.com/docs/guiding-principles
[discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square
[discord]: https://discord.gg/testing-library