I am trying to test functionality of a select element in a React component.
Note: This is not a duplicate of this question because I am not using enzyme, but rather trying to do things simply using act() from React's Test Utilities and running tests with Jest.
Given a component with a select element like this:
class TestSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
choice: "apples",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({choice: event.target.value});
}
render() {
return (
<div>
<select value={this.state.choice} onChange={this.handleChange}>
<option value="apples">apples</option>
<option value="oranges">oranges</option>
</select>
<h4>You like {this.state.choice}</h4>
</div>
);
}
}
I would like to be able to test it like this:
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
test("Should change preference", () => {
act(() => {
render(<TestSelect/>, container);
});
let message = container.querySelector("h4");
expect(message.innerHTML).toContain("apples");
const selectElement = container.querySelector("select");
act(() => {
selectElement.dispatchEvent(new Event("change"), {
target: { value: "oranges"},
bubbles: true,
});
});
message = container.querySelector("h4");
// Test fails here: Value does not change
expect(message.innerHTML).toContain("oranges");
});
After a lot of fiddling and trying different options I am not able to simulate an event that ends up changing the selected value in the select element.