我正在尝试测试React组件中select元素的功能。
注意:这不是this question 的副本,因为我没有使用酶,而是尝试使用React的Test Utilities中的act()
简单地做事并使用Jest运行测试。
给出具有选择元素的组件,如下所示:
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>
);
}
}
我希望能够像这样测试它:
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");
});
经过大量摆弄并尝试了不同的选项之后,我无法模拟一个事件,该事件最终改变了select元素中的所选值。
答案 0 :(得分:2)
我建议您使用React Testing库中的userEvent。
它非常简单易用。 这是提供的示例:
import React from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
test("select values", () => {
const { getByTestId } = render(
<select multiple data-testid="select-multiple">
<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("select-multiple"), ["1", "3"]);
expect(getByTestId("val1").selected).toBe(true);
expect(getByTestId("val2").selected).toBe(false);
expect(getByTestId("val3").selected).toBe(true);
});
答案 1 :(得分:0)
我找到了一种使用Simulate中的react-dom test-utils的方法。
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act, Simulate } 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(() => {
Simulate.change(selectElement, { target: { value: "oranges" }});
});
message = container.querySelector("h4");
expect(message.innerHTML).toContain("oranges");
});