Skip to content

Commit

Permalink
feat(toHaveValue): Asserting aria-valuenow (#479)
Browse files Browse the repository at this point in the history
Co-authored-by: Wayne Van Son <waynevanson@gmail.com>
  • Loading branch information
idanen and waynevanson committed Aug 23, 2024
1 parent 47a667c commit acbf416
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
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
14 changes: 14 additions & 0 deletions src/__tests__/to-have-value.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,18 @@ 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>
<div role="textbox" aria-valuenow="${valueToCheck}" data-testid="textbox"></div>
`)

expect(queryByTestId('meter')).toHaveValue(valueToCheck)
expect(queryByTestId('meter')).not.toHaveValue(valueToCheck + 1)

// Role that does not support aria-valuenow
expect(queryByTestId('textbox')).not.toHaveValue(70)
})
})
14 changes: 12 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,18 +196,28 @@ function getInputValue(inputElement) {
}
}

const rolesSupportingValues = ['meter', 'progressbar', 'slider', 'spinbutton']
function getAccessibleValue(element) {
if (!rolesSupportingValues.includes(element.getAttribute('role'))) {
return undefined
}
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

0 comments on commit acbf416

Please sign in to comment.