React-testing-library getByRole is performing extremely slowly
Asked Answered
S

1

12

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?

Sibelius answered 25/10, 2021 at 16:47 Comment(2)
Have you considered using within to only query within certain elements and avoid traversing the whole DOM?Waller
@Waller thanks for the suggestion, we hadn't tried that. Preliminary tests showed that the time (running locally, the numbers above are in Jenkins) reduced from around 5800ms to around 5400ms for the query above. Which is unfortunately not much betterSibelius
I
3

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.

Inharmonious answered 9/3, 2022 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.