typescript 测试在React测试库中选择选择选项时显示输入字段

wgeznvg7  于 2023-03-09  发布在  TypeScript
关注(0)|答案(1)|浏览(153)

我有一个选择字段和一个输入字段,我想为它们创建一个测试,以便在选择选项为“女性”时显示输入字段“年龄”。但我得到了一个错误,有人能帮助我吗?
错误:测试库元素错误:找不到角色为“textbox”且名称为/age/i的可访问元素

const genderOption = watch("gender");

    <input name="gender" role="combobox">
      <button class="combobox-arrow"></button>
      <ul role="listbox">
       <li
        role="option"
        value="Male"
       ><span>Male</span></li>
       <li
        role="option"
        value="Female"
       ><span>Female</span></li>
      </ul>
    {genderOption === "Female" && (
      <label for="ageInput">Age</label>
      <input
      id="ageInput"
      type="text"
      name="Age"
      >
    )}
const genderInput = screen.getByRole("combobox", {
    name: /gender/i,
  });

  userEvent.click(genderInput);
  const optionElement = screen.getByRole("option", {
    name: /female/i,
  });
  await userEvent.click(optionElement);

  const ageElement = screen.getByRole("textbox", {
    name: /age/i,
  });
lnxxn5zx

lnxxn5zx1#

使用React Testing Library测试元素的出现和消失有时候很难完全准确地把握时间,您应该使用findByX查询来等待元素出现。
https://testing-library.com/docs/guide-disappearance/#1-using-findby-queries

const genderInput = screen.getByRole("combobox", {
    name: /gender/i,
  });

  userEvent.click(genderInput);
  const optionElement = screen.getByRole("option", {
    name: /female/i,
  });
  await userEvent.click(optionElement);

  const ageElement = await screen.findByRole("textbox", {
    name: /age/i,
  });

相关问题