Skip to content

Commit acbf416

Browse files
idanenwaynevanson
andauthored
feat(toHaveValue): Asserting aria-valuenow (#479)
Co-authored-by: Wayne Van Son <[email protected]>
1 parent 47a667c commit acbf416

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -996,6 +996,9 @@ It accepts `<input>`, `<select>` and `<textarea>` elements with the exception of
996996
matched only using [`toBeChecked`](#tobechecked) or
997997
[`toHaveFormValues`](#tohaveformvalues).
998998

999+
It also accepts elements with roles `meter`, `progressbar`, `slider` or
1000+
`spinbutton` and checks their `aria-valuenow` attribute (as a number).
1001+
9991002
For all other form elements, the value is matched using the same algorithm as in
10001003
[`toHaveFormValues`](#tohaveformvalues) does.
10011004

src/__tests__/to-have-value.js

+14
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,18 @@ Received:
203203
<red> foo</>
204204
`)
205205
})
206+
207+
test('handles value of aria-valuenow', () => {
208+
const valueToCheck = 70
209+
const {queryByTestId} = render(`
210+
<div role="meter" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${valueToCheck}" data-testid="meter"></div>
211+
<div role="textbox" aria-valuenow="${valueToCheck}" data-testid="textbox"></div>
212+
`)
213+
214+
expect(queryByTestId('meter')).toHaveValue(valueToCheck)
215+
expect(queryByTestId('meter')).not.toHaveValue(valueToCheck + 1)
216+
217+
// Role that does not support aria-valuenow
218+
expect(queryByTestId('textbox')).not.toHaveValue(70)
219+
})
206220
})

src/utils.js

+12-2
Original file line numberDiff line numberDiff line change
@@ -196,18 +196,28 @@ function getInputValue(inputElement) {
196196
}
197197
}
198198

199+
const rolesSupportingValues = ['meter', 'progressbar', 'slider', 'spinbutton']
200+
function getAccessibleValue(element) {
201+
if (!rolesSupportingValues.includes(element.getAttribute('role'))) {
202+
return undefined
203+
}
204+
return Number(element.getAttribute('aria-valuenow'))
205+
}
206+
199207
function getSingleElementValue(element) {
200208
/* istanbul ignore if */
201209
if (!element) {
202210
return undefined
203211
}
212+
204213
switch (element.tagName.toLowerCase()) {
205214
case 'input':
206215
return getInputValue(element)
207216
case 'select':
208217
return getSelectValue(element)
209-
default:
210-
return element.value
218+
default: {
219+
return element.value ?? getAccessibleValue(element)
220+
}
211221
}
212222
}
213223

0 commit comments

Comments
 (0)