Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine complex selectors

We are faced with a more complex UI we want to test:

# Section Header A

 - Option 1
   [ ] checkbox
 - Option 2
   [ ] checkbox

# Section Header B

 - Option 1
   [ ] checkbox

I want to find the checkbox in Option 1 of Section Header A, or in pseudo-code:

chain(
  getByRole('fieldset', {name: 'Section Header A'}),
  getByText('Option 1'),
  getByRole('checkbox')
)

Currently we have solved this via:

import {
  getByText as globalGetByText,
  getByRole as globalGetByRole,
} from '@testing-library/dom';

const { container } = render(<MyComponent />);
const sectionA = globalGetByRole(container, 'fieldset', {name: 'Section Header A'}),
const option1 = globalGetByText(sectionA, 'Option 1'),
const finallyMyElement = globalGetByRole(option1, 'checkbox')

Note the global... import renaming to avoid clashes with the regular getBy* queries and passing the container reference explicitly.

We are not using testids, as per the spirit of react-testing-library.

Is there a more intuitive way?

like image 287
cburgmer Avatar asked May 23 '26 04:05

cburgmer


1 Answers

It seems within() solves my problem (https://testing-library.com/docs/dom-testing-library/api-within):

const { getByRole } = render(<MyComponent />);
const sectionA = getByRole('fieldset', {name: 'Section Header A'});
const option1 = within(sectionA).getByText('Option 1');
const finallyMyElement = within(option1).getByRole('checkbox');

Mind you, this is untested.

like image 127
cburgmer Avatar answered May 30 '26 15:05

cburgmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!