testing-library / dom-testing-library

🐙 Simple and complete DOM testing utilities that encourage good testing practices.
https://testing-library.com/dom
MIT License
3.25k stars 460 forks source link

Support complex aria-labelledby queries #1281

Closed jossmac-plenti closed 6 months ago

jossmac-plenti commented 6 months ago

Describe the feature you'd like:

I'd like getByLabelText to resolve the contents of aria-labelledby and associated elements. As I'm writing this it occurs to me that this might be too costly and perhaps better suited to something like axe.

Describe alternatives you've considered:

I've resorted to a combination of getByRole + getByText and checking IDs.

Teachability, Documentation, Adoption, Migration Strategy:

The summarised/pseudo code looks something like:

let contentId = 'content-id';
let spinnerId = 'spinner-id';

return (
  <button
    aria-disabled={props.pending ? true : undefined}
    aria-labelledby={props.pending ? `${contentId} ${spinnerId}` : undefined}
  >
    <span id={contentId}>{props.children}</span>
    {props.pending && (
      <span id={spinnerId} aria-label="pending" aria-hidden>
        ...
      </span>
    )}
  </button>
);

The desired test would look something like:

it('supports "pending" prop', () => {
  let buttonText = 'Submit';
  let { getByLabelText } = render(<Button pending>{buttonText}</Button>);

  expect(getByLabelText(`${buttonText} pending`)).toHaveAttribute("aria-disabled", true);
});
jossmac-plenti commented 6 months ago

Moved to https://github.com/testing-library/react-testing-library/issues/1260