在 response-test-library 中通过 id 查找元素

我正在使用 反应测试图书馆来测试我的反应应用程序。出于某种原因,我需要能够找到的元素的 id,而不是 data-testid。在文档中无法实现这一点。

有办法做到吗?

我将呈现的输出作为:

const dom = render(<App />);

我在找一些类似于:

const input = dom.getElemenById('firstinput');
//or
const input = dom.getById('firstinput');
139375 次浏览

It looks you have DOM node itself as a container. Therefore, you should be able to call .querySelector('#firstinput') with that.

I found a way to do this.

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');

I hope this helps.

There are two ways to do so

  1. Simply use container.getElementById('id'). In the end, all the helpers are doing is making queries like this one under the hood
  2. If you want to have your custom query you can write a custom render. Check the documentation for more info https://github.com/kentcdodds/react-testing-library#getbytestidtext-textmatch-htmlelement

As a final note, if you can avoid looking for elements by id it's better.

You can set up with testIdAttribute in the configuration.

configure({ testIdAttribute: 'id' })

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


The setting has pros and cons. The benefit of it is that you can set an id for multiple uses. (Test id, marketing analytics, tag manager, ...etc) You don't have to add both id and test-id. It's good for the conciseness of the code.

But be careful, you might accidentally set the same id at two different components on the same page. Remember to add index or identification to a component id for list items.

I feel like none of the answers really gave a complete solution, so here it is:

const result = render(<SomeComponent />);
const someElement = result.container.querySelector('#some-id');

My advice: stop adding and searching by ids, this always takes to much time and effort because you have to add the ids (sometimes test-ids) and then find out the best way to query the element. But even if you really need an id, this tool will save you a lot of time by showing the best way to query any DOM element on your screen: Testing Playground

If you use TypeScript, and want to get a non-null result, here's a convenience function:

function getById<T extends Element>(container: HTMLElement, id: string): T {
const element = container.querySelector<T>(`#${id}`);
assert(element !== null, `Unable to find an element with ID #${id}.`)
return element;
}

You can then use it like this:

import { render } from '@testing-library/react';


const { container } = render(<App />);
const myInputElement = getById<HTMLInputElement>(container, 'myInputElement');