【问题标题】:What is the difference "getByText" and "getByTestId" ? In testing-library/react"getByText" 和 "getByTestId" 有什么区别?在测试库/反应
【发布时间】:2020-11-25 08:26:34
【问题描述】:

getByTextgetByTestId 有什么区别?

当我测试一个 React 组件时,这两个函数之间存在一些差距。

getByText 代码中测试失败,但在getByTestId 中成功。

我有代码,当单击一个元素时,标题的颜色变为红色。

为什么会这样?

我省略了 ContainerContent 的样式组件。这使道具“切换”以将颜色更改为红色。

这里是getByText 代码:

const { getByText } = render(<ListPresenter content={ListText} />);
const colorChangedText = getByText(/the party/);
fireEvent.click(colorChangedText);
screen.debug(); // The result of render I want !
expect(colorChangedText).toHaveStyle("color: red");    * failed

这里是getByTestId 代码:

const { getByText } = render(<ListPresenter content={ListText} />);
fireEvent.click(getAllByTestId("list-element-toggle")[0]);
screen.debug(); // The result of render I want !
const colorChangedText = getAllByTestId("list-element-content")[0];
expect(colorChangedText).toHaveStyle("color: red");   * success

这是渲染的组件:

const Component = (props) => {
  return (
    <Container
        className="container"
        data-testid={"list-element-toggle"}
        toggled={state[data.id - 1]}
     >
        <Content className="content" data-testid={"list-element-content"} toggled={state[data.id - 1]}>
          {data.titleChild}.  // This text had been changed to red color when i was clicked.
        
        </div>
      </div>
  )
}

【问题讨论】:

  • 我建议尽可能使用 getByText,然后它遵循测试用户所见所闻的精神,即不测试实现细节。 getByTestId 仅当您无法从 UI 中轻松锁定任何内容时。 getByTestId:用户无法看到(或听到)这些,因此仅建议在无法按角色或文本匹配或没有意义(例如文本是动态的)的情况下使用。 testing-library.com/docs/guide-which-query

标签: reactjs testing styled-components react-testing-library


【解决方案1】:

react-testing-library cheetsheet

  • ByText 按元素查找文本内容
  • ByTestId 按 data-testid 属性查找

我发现按文本选择可能有点挑剔,通常最终会添加一个 testid 属性来查询/定位我想要的 exact 元素。

我的猜测是getByText 可能没有返回正确的元素/包装器。

来自您的测试代码

render(<ListPresenter content={ListText} />);

我不清楚测试中的文本可能是什么。我什至不清楚ListPresenter 是否是最后一个sn-p 中的Component。比如data.titleChild是什么?

另见Which query should I use?

每个人都可以访问的查询

getByText: 对表单没用,但这是第 1 种方法 用户可以找到大多数非交互式元素(例如 div 和 span)。

测试 ID

getByTestId: 用户看不到(或听到)这些,所以这只是 推荐用于无法按角色或文本匹配的情况 没有意义(例如,文本是动态的)。

作为后备还有Manual Queries

【讨论】:

    猜你喜欢
    • 2021-06-09
    • 2020-03-06
    • 1970-01-01
    • 2011-07-15
    • 2011-02-14
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多