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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,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 @@ -197,18 +197,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'))
}

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