Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(toHaveValue): Asserting aria-valuenow #479

Merged
merged 5 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,9 @@ It accepts `<input>`, `<select>` and `<textarea>` elements with the exception of
matched only using [`toBeChecked`](#tobechecked) or
[`toHaveFormValues`](#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`](#tohaveformvalues) does.

Expand Down
10 changes: 10 additions & 0 deletions src/__tests__/to-have-value.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,14 @@ Received:
<red> foo</>
`)
})

test('handles value of aria-valuenow', () => {
const valueToCheck = 70
const {queryByTestId} = render(`
<div role="meter" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${valueToCheck}" data-testid="meter"></div>
`)

expect(queryByTestId('meter')).toHaveValue(valueToCheck)
expect(queryByTestId('meter')).not.toHaveValue(valueToCheck + 1)
})
})
16 changes: 14 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,18 +196,30 @@ function getInputValue(inputElement) {
}
}

const rolesSupportingValues = ['meter', 'progressbar', 'slider', 'spinbutton']
function getAccessibleValue(element) {
if (!rolesSupportingValues.includes(element.getAttribute('role'))) {
return
}
// We want same behavior as accessing the `value` property
// eslint-disable-next-line consistent-return
return Number(element.getAttribute('aria-valuenow'))
}
idanen marked this conversation as resolved.
Show resolved Hide resolved

function getSingleElementValue(element) {
/* istanbul ignore if */
if (!element) {
return undefined
}

switch (element.tagName.toLowerCase()) {
case 'input':
return getInputValue(element)
case 'select':
return getSelectValue(element)
default:
return element.value
default: {
return element.value ?? getAccessibleValue(element)
}
}
}

Expand Down
Loading