QuerySelectorAll in React Testing Library?
Asked Answered
A

3

11

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?

Advertent answered 23/9, 2020 at 23:53 Comment(3)
Hi, interesting not sure if this might be of interest github.com/testing-library/react-testing-library/issues/526Jarrodjarrow
Thank you. Any alternatives would be appreciatedAdvertent
getAllBy, queryAllBy, findAllBy... testing-library.com/docs/dom-testing-library/cheatsheet/… You have many options, you can also install the testing library dev tools to help you find the correct selectors...Reluctivity
B
10

You can do this by using querySelectorAll instead of querySelector.

container
      .querySelectorAll('div[tabindex]').forEach(eachAccordian => {
        expect(eachAccordian).toHaveAttribute('aria-expanded', 'false')
      })
Burbot answered 23/7, 2021 at 11:25 Comment(0)
L
3

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!

Lovemaking answered 24/9, 2020 at 0:5 Comment(3)
Thank you for your response. Can you give me an example? How can i use queryAllBy in this example?Advertent
Like let's say that you give your dropdowns a data-test-id="dropdown", then you can make a custom query helper like the one here (the queryAllByTestId): testing-library.com/docs/dom-testing-library/…Lovemaking
you can get all : const elements = queryAllByLabelText('myLabel') then lets say you wanna test the if the first one is a certain element, you can use destructering for example: [ firstEl ] = elements then expect it to have a certain value...Reluctivity
M
0

It seems "getByRole" solves many querySelector requirements.

Roles: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#roles

Mindy answered 11/11, 2022 at 1:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.