Skip to content

Commit

Permalink
Add logic for this special case, and updated docs.
Browse files Browse the repository at this point in the history
Co-authored-by: Caroline Tan <[email protected]>
  • Loading branch information
winstonwolff and carolinectan committed Jul 8, 2024
1 parent e72cd02 commit b833800
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -850,8 +850,11 @@ of all cases covered:
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
as an **array** containing all the values of the checkboxes in the
collection.
- a hidden input with same name before the checkbox is allowed which is a
common workaround to allow browsers to send `false` for unchecked
checkboxes.
- `<input type="radio">` 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
Expand Down
8 changes: 5 additions & 3 deletions src/__tests__/to-have-form-values.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,15 @@ describe('.toHaveFormValues', () => {
it('allows a checkbox and a hidden input which is a common workaround so forms can send "false" for a checkbox', () => {
const {container} = render(`
<form>
<input type="hidden" name="sample-checkbox" value=0>
<input type="checkbox" name="sample-checkbox" value=1>
<input type="hidden" name="checkbox-with-hidden-false" value=0>
<input type="checkbox" name="checkbox-with-hidden-false" value=1>
</form>
`)
const form = container.querySelector('form')
expect(() => {
expect(form).toHaveFormValues({ "sample-checkbox": 1})
expect(form).toHaveFormValues({
'checkbox-with-hidden-false': ['0', '1'],
})
}).not.toThrowError()
})

Expand Down
15 changes: 12 additions & 3 deletions src/to-have-form-values.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,18 @@ import {
function getMultiElementValue(elements) {
const types = [...new Set(elements.map(element => element.type))]
if (types.length !== 1) {
throw new Error(
'Multiple form elements with the same name must be of the same type',
)
if (
types.length === 2 &&
types[0] === 'hidden' &&
types[1] === 'checkbox'
) {
// Allow the special case where there's a 'checkbox' input, and a matching 'hidden' input
// before it, which works around browser forms so a 'false' value is submitted.
} else {
throw new Error(
'Multiple form elements with the same name must be of the same type',
)
}
}
switch (types[0]) {
case 'radio': {
Expand Down

0 comments on commit b833800

Please sign in to comment.