Find element by id in react-testing-library

Viewed 125162

I'm using react-testing-libarary to test my react application. For some reason, I need to be able to find the element by id and not data-testid. There is no way to achieve this in the documentation.

Is there a way to achieve this?

I've the rendered output as:

const dom = render(<App />);

I'm looking for something in line of:

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

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

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.

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

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.

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