Skip to content

Commit

Permalink
Merge pull request #158 from testing-library/select
Browse files Browse the repository at this point in the history
fix: fire onChange event on select element change
  • Loading branch information
Gpx authored Aug 27, 2019
2 parents 1303a79 + fe018f3 commit 00f8f05
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
21 changes: 21 additions & 0 deletions __tests__/react/selectoptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,27 @@ describe("userEvent.selectOptions", () => {
expect(getByTestId("val3").selected).toBe(false);
});

it("should fire onChange event on a SELECT element", () => {
const onChangeHandler = jest.fn();

const { getByTestId } = render(
<select data-testid="element" onChange={onChangeHandler}>
<option data-testid="val1" value="1">
1
</option>
<option data-testid="val2" value="2">
2
</option>
<option data-testid="val3" value="3">
3
</option>
</select>);

userEvent.selectOptions(getByTestId("element"), "2");

expect(onChangeHandler).toBeCalled();
});

it("sets the selected prop on the selected OPTION using nested SELECT", () => {
const onSubmit = jest.fn();

Expand Down
8 changes: 5 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ function dblClickCheckbox(checkbox) {
fireEvent.click(checkbox);
}

function selectOption(option) {
function selectOption(select, option) {
fireEvent.mouseOver(option);
fireEvent.mouseMove(option);
fireEvent.mouseDown(option);
Expand All @@ -88,6 +88,8 @@ function selectOption(option) {
fireEvent.click(option);

option.selected = true;

fireEvent.change(select);
}

function fireChangeEvent(event) {
Expand Down Expand Up @@ -162,9 +164,9 @@ const userEvent = {

if (selectedOptions.length > 0) {
if (element.multiple) {
selectedOptions.forEach(option => selectOption(option));
selectedOptions.forEach(option => selectOption(element, option));
} else {
selectOption(selectedOptions[0]);
selectOption(element, selectedOptions[0]);
}
}

Expand Down

0 comments on commit 00f8f05

Please sign in to comment.