Dom-testing-library: within for mutliple elements

Created on 20 Dec 2019  路  9Comments  路  Source: testing-library/dom-testing-library

Describe the feature you'd like:

I'm aware of the callback function that allows you to accomplish this, but we've seen this pattern emerge enough times that it made me wonder if the ability to combine queries would be possible, and maybe make the tests a little more readable:

i.e. if i want to combine getByText & getByRole i know I can do this:

getByText((text, element => text === "Have an issue?" && element.getAttribute('role') === 'button'))

it would be nice to do something like this:

within(getAllByRole("button")).getByText("Have an issue?")

Suggested implementation:

modify within to accept a NodeList / array perhaps?

Describe alternatives you've considered:

none that i can think of

Teachability, Documentation, Adoption, Migration Strategy:

enhancement help wanted

Most helpful comment

馃帀 I submitted issue #420 What a stony milestone!

All 9 comments

馃帀 I submitted issue #420 What a stony milestone!

ah yeah i was actually initially going to post that here, but as I was talking with a colleague, it occurred to me it might be a bit cleaner to just use the existing testing-lib apis ala within . I think it would actually be pretty easy to implement...

@kentcdodds any thoughts on this?

Hi 馃憢

Hmm... I think that's ok. I don't know how many people would use that feature, but I don't see harm in adding it. Should be pretty simple as you said. Feel free to open a pull request for it.

within(getAllByRole("button")).getByText("Have an issue?")

Now that we have getAllByRole('button', { name: 'Have an issue?' }) why would we need another API? It seems like these would do the same thing.

I agree with @eps1lon here. This use case is well covered.

@eps1lon and @kentcdodds are there examples you can point me towards where the name option is being used?

I'm trying the following:

test('Buttons',  () => {
  const {getAllByRole} = render(
    <div>
      <button>foo</button>
      <button>bar</button>
    </div>
  );

  const buttons = getAllByRole('button', {name: 'foo'});
})

In this case, buttons is an array of both buttons, NOT just the first button as I'd expect. Am I doing something incorrect here?

I've poured over the docs and while I do see where this concept is explained, I haven't found an example that shows it working.

@Jiert are you on the latest version of the library? The name option would be ignored on older versions of getAllByRole, returning all the buttons.

@alexkrolick well don't I feel embarrassed. That was it, thanks so much!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

icfantv picture icfantv  路  4Comments

ruscal picture ruscal  路  3Comments

EvgenyOrekhov picture EvgenyOrekhov  路  3Comments

PaulInglis picture PaulInglis  路  3Comments

eliyaomid picture eliyaomid  路  3Comments