58

我正在使用react-testing-libarary来测试我的反应应用程序。出于某种原因,我需要能够通过idand not找到元素data-testid。在文档中没有办法实现这一点。

有没有办法做到这一点?

我将渲染输出为:

const dom = render(<App />);

我正在寻找符合以下条件的东西:

const input = dom.getElemenById('firstinput');
//or 
const input = dom.getById('firstinput');
4

6 回答 6

82

我觉得没有一个答案真正给出了完整的解决方案,所以这里是:

const result = render(<SomeComponent />);
const someElement = result.container.querySelector('#some-id');
于 2020-11-12T11:08:32.397 回答
54

我找到了一种方法来做到这一点。

import App from './App';
import { render, queryByAttribute } from 'react-testing-library';

const getById = queryByAttribute.bind(null, 'id');

const dom = render(<App />);
const table = getById(dom.container, 'directory-table');

我希望这有帮助。

于 2018-10-26T07:52:46.420 回答
26

看起来您将 DOM 节点本身作为容器。因此,您应该可以使用它进行调用.querySelector('#firstinput')

于 2018-10-26T07:33:38.717 回答
8

有两种方法可以做到这一点

  1. 只需使用container.getElementById('id'). 最后,所有助手所做的都是在后台进行类似这样的查询
  2. 如果您想要自定义查询,您可以编写自定义渲染。查看文档以获取更多信息https://github.com/kentcdodds/react-testing-library#getbytestidtext-textmatch-htmlelement

最后一点,如果您可以避免通过 id 查找元素,那就更好了。

于 2018-10-26T07:55:50.247 回答
6

您可以testIdAttribute在配置中进行设置。

configure({ testIdAttribute: 'id' })

https://testing-library.com/docs/dom-testing-library/api-configuration


设定有利有弊。这样做的好处是您可以设置一个 id 用于多种用途。(测试 id、营销分析、标签管理器等)您不必同时添加 id 和 test-id。这有利于代码的简洁。

但要小心,您可能会不小心在同一页面上的两个不同组件上设置了相同的 id。请记住将索引或标识添加到列表项的组件 ID。

于 2020-10-08T09:57:14.043 回答
2

我的建议:停止添加和按 id 搜索,这总是需要花费大量时间和精力,因为您必须添加 id(有时是 test-id),然后找出查询元素的最佳方法。但即使你真的需要一个 id,这个工具也会通过显示查询屏幕上任何 DOM 元素的最佳方式来为你节省大量时间:Testing Playground

于 2021-05-25T14:45:33.277 回答