测试与 Jest 反应的选择元素

Ada*_*m D 1 javascript reactjs jestjs

我正在尝试测试 React 组件中 select 元素的功能。

注意:这不是这个问题的重复,因为我没有使用酶,而是尝试简单地使用act()React 的测试实用程序并使用Jest运行测试。

给定一个带有 select 元素的组件,如下所示:

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够像这样测试它:

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");
});
Run Code Online (Sandbox Code Playgroud)

经过大量摆弄和尝试不同的选项后,我无法模拟最终更改 select 元素中选定值的事件。

Arn*_*del 6

我建议您使用React 测试库中的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);
});
Run Code Online (Sandbox Code Playgroud)