Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-testing-library getByRole is performing extremely slowly

We have noticed that our unit tests are performing very slowly and the culprit seems to be getByRole for querying for button elements etc. Here is an example of a query that was giving us problems today:

userEvent.click(screen.getAllByRole('button', { name: 'Accept' })[0]);

Using console.time() we measured this query as taking 12782ms to execute. After switching to getByText the query takes 14ms, meaning that getByRole is taking nearly 1000x longer (!!!).

I know that getByRole is expected to run slower, but it seems extreme. I've found threads online detailing how some tests took 5x longer but nothing like this. Adding hidden: true as an option speeds things up a little but not by a massive amount.

I'm unable to share the code that is being tested as it is private. I wouldn't describe the component as particularly complex, although it is comprised of a few lower-level components and uses mocked out network requests.

Are there any known reasons for slow running queries like this, or any ways we can speed up execution without sacrificing the confidence that getByRole offers?

like image 628
FlinnBurgess Avatar asked Feb 14 '26 02:02

FlinnBurgess


1 Answers

The getByRole query needs to search thru the entire accessibility tree and visibility check(in terms of accessibility), which involves not-ignorable style calculation and aria-* calculation.

The slowness is also discussed here https://github.com/testing-library/dom-testing-library/issues/552#issuecomment-625172052

I think it's a trade-off b/w confidence(in trusting your page is accessible) and test-speed.

One quick way to speed up is to configure the defaultHidden testing library configuration, which I saw ~4x speed up but again it's a trade-off since it does not check the target element visibility in the accessibility tree.

like image 146
Liu Nate Avatar answered Feb 16 '26 18:02

Liu Nate