我有一个 SelectExample.js
import React, { useState } from "react";
import { InputLabel, MenuItem, FormControl, Select, Typography } from "@mui/material";>
export default function SelectExample() {
const [country, setCountry] = useState([]);
return (
<div>
<Typography variant="h6">Selected country: {country}</Typography>
<FormControl>
<InputLabel data-testid="country2" id="country">Country</InputLabel>
<Select
multiple
data-testid="country"
onChange={({ target: { value } }) => setCountry(value)}
value={country}
style={{ minWidth: 120 }}
>
<MenuItem value="brazil">Brazil</MenuItem>
<MenuItem value="japan">Japan</MenuItem>
<MenuItem value="usa">United States</MenuItem>
</Select>
</FormControl>
</div>
)}
和 SelectExample.test.js
import React from "react";
import { getByDisplayValue, getByRole, render, screen, waitFor } from "@testing-library/react";
import UserEvent from "@testing-library/user-event";
import "@testing-library/jest-dom/extend-expect";
import { act } from "react-dom/test-utils";
import SelectExample from "./SelectExample";
test("select", async () => {
await act(async () => await render(<SelectExample />));
UserEvent.click(getByRole(screen.getByTestId("country"), "button"));
await waitFor(() => UserEvent.click(screen.getByText(/brazil/i)));
UserEvent.click(getByRole(screen.getByTestId("country"), "button")); // this line do not perform the expected behaviour
// would like to assert if brazil is in the document
screen.debug()
});
我想在开始测试之前执行一些用户操作:
对于步骤 1 和步骤 2。效果很好。但对于Step3。有一些问题... 如果我在选择巴西后为我的按钮再添加一个点击事件。出现以下错误:
如果我删除该行,就不会发生这种情况。 我不明白为什么会出现这个错误。以及如何执行步骤 3 进行测试
await user.keyboard("{Tab}")
到目前为止,这段代码只对我有用。 注意:在您的情况下将 user 替换为 UserEvent