Skip to content

Commit

Permalink
feat: allow selecting options by nodes (#297)
Browse files Browse the repository at this point in the history
  • Loading branch information
Doug Bacelar committed May 26, 2020
1 parent 6239c3a commit 41f71b5
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 2 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -272,6 +272,15 @@ test('selectOptions', () => {
The `values` parameter can be either an array of values or a singular scalar
value.

It also accepts option nodes:

```js
userEvent.selectOptions(screen.getByTestId('select-multiple'), [
screen.getByText('A'),
screen.getByText('B'),
])
```

### `tab({shift, focusTrap})`

Fires a tab event changing the document.activeElement in the same way the
Expand Down
27 changes: 27 additions & 0 deletions src/__tests__/selectoptions.js
Expand Up @@ -168,6 +168,33 @@ test('sets the selected prop on the selected OPTION', () => {
expect(screen.getByTestId('val3').selected).toBe(true)
})

test('sets the selected prop on the selected OPTION using nodes', () => {
render(
<form onSubmit={() => {}}>
<select multiple data-testid="element">
<option data-testid="val1" value="1">
first option
</option>
<option data-testid="val2" value="2">
second option
</option>
<option data-testid="val3" value="3">
third option
</option>
</select>
</form>,
)

userEvent.selectOptions(screen.getByTestId('element'), [
screen.getByText('second option'),
screen.getByText('third option'),
])

expect(screen.getByTestId('val1').selected).toBe(false)
expect(screen.getByTestId('val2').selected).toBe(true)
expect(screen.getByTestId('val3').selected).toBe(true)
})

test('sets the selected prop on the selected OPTION using htmlFor', () => {
const onSubmit = jest.fn()

Expand Down
2 changes: 1 addition & 1 deletion src/index.js
Expand Up @@ -270,7 +270,7 @@ function selectOptions(element, values, init) {
const valArray = Array.isArray(values) ? values : [values]
const selectedOptions = Array.from(
element.querySelectorAll('option'),
).filter(opt => valArray.includes(opt.value))
).filter(opt => valArray.includes(opt.value) || valArray.includes(opt))

if (selectedOptions.length > 0) {
if (element.multiple) {
Expand Down
6 changes: 5 additions & 1 deletion typings/index.d.ts
Expand Up @@ -22,7 +22,11 @@ declare const userEvent: {
clear: (element: TargetElement) => void
click: (element: TargetElement, init?: MouseEventInit) => void
dblClick: (element: TargetElement, init?: MouseEventInit) => void
selectOptions: (element: TargetElement, values: string | string[], init?: MouseEventInit) => void
selectOptions: (
element: TargetElement,
values: string | string[] | HTMLElement | HTMLElement[],
init?: MouseEventInit,
) => void
upload: (
element: TargetElement,
files: FilesArgument,
Expand Down

0 comments on commit 41f71b5

Please sign in to comment.