`getByRole` 找不到相应文本框的名称

Srd*_*No1 6 reactjs react-testing-library

这是针对 的测试:

  it("changes the state when body input is changed", () => {
    render(<CommentForm />)
    // let input = screen.getByLabelText("Your Name");

    let input = screen.getByRole("textbox", { name: "Your Comment" });
    fireEvent.change(input, { target: { value: "MyComment" } });
    expect(input.value).toEqual("MyComment");
  });

Run Code Online (Sandbox Code Playgroud)

使用注释行它可以工作(当我使用 搜索时getByLabelText)。这是当我尝试使用以下命令找到它时得到的结果getByRole

 Unable to find an accessible element with the role "textbox" and name "Your Comment"

    Here are the accessible roles:

      document:

      Name "":
      <body />

      --------------------------------------------------
      generic:

      Name "":
      <div />

      Name "":
      <div
        class="input-group"
      />

      Name "":
      <div
        class="input-group"
      />

      --------------------------------------------------
      heading:

      Name "Post a Comment":
      <h2 />

      --------------------------------------------------
      textbox:

      Name "Your Name":
      <input
        id="author-name"
        name="author"
        type="text"
        value=""
      />

      Name "":
      <textarea
        cols="30"
        id="body"
        name="body"
        rows="10"
      />

Run Code Online (Sandbox Code Playgroud)

所以看起来这个名字是空的,但我不确定为什么会这样。

这是实际的组件:

 Unable to find an accessible element with the role "textbox" and name "Your Comment"

    Here are the accessible roles:

      document:

      Name "":
      <body />

      --------------------------------------------------
      generic:

      Name "":
      <div />

      Name "":
      <div
        class="input-group"
      />

      Name "":
      <div
        class="input-group"
      />

      --------------------------------------------------
      heading:

      Name "Post a Comment":
      <h2 />

      --------------------------------------------------
      textbox:

      Name "Your Name":
      <input
        id="author-name"
        name="author"
        type="text"
        value=""
      />

      Name "":
      <textarea
        cols="30"
        id="body"
        name="body"
        rows="10"
      />

Run Code Online (Sandbox Code Playgroud)

任何人都可以看到这里的问题。我确信它应该有效,而且我看不出有任何理由可以用getByRole名称来获取作者的输入,但这个不能。

小智 0

我想,你textarea已经有了name=body,你正在寻找name=Your Comment。尝试使用body代替。