Dom-testing-library: Add new getByRole queryselector.

Created on 4 Sep 2018  路  4Comments  路  Source: testing-library/dom-testing-library

Describe the feature you'd like:

A new querySelector to select elements based on role. I have a dialog that while I can query inside the dialog just fine I cannot first a click to close the dialog because all the current queries target elements inside the dialog so the out of bounds click handlers do not fire.

Suggested implementation:

const queryAllByRole = queryAllByAttribute.bind(null, 'role')

const queryByRole = queryByAttribute.bind(null, 'role')
const queryAllByRole = queryAllByAttribute.bind(null, 'role')

function getAllByRole(container, id, ...rest) {
  const els = queryAllByRole(container, id, ...rest)
  if (!els.length) {
    throw getElementError(
      `Unable to find an element by role=${id}`,
      container,
    )
  }
  return els
}

function getByRole(...args) {
  return firstResultOrNull(getAllByRole, ...args)
}

Describe alternatives you've considered:

I'm using Material UI where there is a lot of abstraction in DOM that I can't put data-testid on the outer dialog. So targeting it by testid won't work for triggering the onClose event.

The only thing I've considered is writing the
const dialogConstainer = container.querySelector('[role="dialog"]')
And then writing assertions from there.

Teachability, Documentation, Adoption, Migration Strategy:

This is a non breaking change as it is only an addition to the existing query set.


getByRole

getByRole(
  container: HTMLElement,
  text: TextMatch,
  options?: {
    exact?: boolean = true,
    collapseWhitespace?: boolean = false,
    trim?: boolean = true,
  }): HTMLElement`

A shortcut to container.querySelector(`[role="${yourRole}"]`) (and it
also accepts a TextMatch).

// <div role="dialog">...</div>
const dialogContainer = getByTestrole(container, 'dialog')

Most helpful comment

Can do I'll have a PR later today.

All 4 comments

Funny, I was thinking something similar now after the recent discussion in gnapse/jest-dom#55. It would be a nice addition.

Thanks for the thorough feature request @JeffBaumgardt! I'm in favor of this. Would you like to implement it?

Can do I'll have a PR later today.

Closed via #94

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eliyaomid picture eliyaomid  路  3Comments

EvgenyOrekhov picture EvgenyOrekhov  路  3Comments

sompylasar picture sompylasar  路  3Comments

icfantv picture icfantv  路  4Comments

dlbnco picture dlbnco  路  3Comments