QuerySelectorAll in React Testing Library?

Viewed 23699

Question: I have multiple dropdowns and I am checking to see if any of them are open. How can i do this in React testing library? (I'm going through bunch of tabIndexes and checking through them)

Issue: container.querySelectorAll isn't possible in react testing library.

Code:

it('should not expand dropdown for multiple view', () => {
    const { container } = render(
      getMockedComponent()
    )

    expect(container).toBeVisible()

    container
      .querySelector('div[tabindex]').forEach(eachAccordian => {
        expect(eachAccordian).toHaveAttribute('aria-expanded', 'false')
      })
 })

How can i check all the nodes using React testing library?

2 Answers

You can do this by using querySelectorAll instead of querySelector.

container
      .querySelectorAll('div[tabindex]').forEach(eachAccordian => {
        expect(eachAccordian).toHaveAttribute('aria-expanded', 'false')
      })

You might want to use the React Testing Library queries instead of querySelector. queryAllBy should probably get you what you need, where you can select anything with a certain data-test-id or role, and check their attributes from there!

Related