react-testing-library:无法关闭 MUI Select 的下拉菜单

问题描述 投票:0回答:1

我有一个 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 步:用户选择“巴西”->“巴西”出现在“国家/地区”文本下
  • 第 3 步:用户单击“国家/地区”按钮一次 -> 关闭下拉菜单

对于步骤 1 和步骤 2。效果很好。但对于Step3。有一些问题... 如果我在选择巴西后为我的按钮再添加一个点击事件。出现以下错误:

如果我删除该行,就不会发生这种情况。 我不明白为什么会出现这个错误。以及如何执行步骤 3 进行测试

reactjs unit-testing jestjs react-testing-library
1个回答
0
投票
await user.keyboard("{Tab}")

到目前为止,这段代码只对我有用。 注意:在您的情况下将 user 替换为 UserEvent

© www.soinside.com 2019 - 2024. All rights reserved.