13

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?

3

3 Answers 3

11

You can do this by using querySelectorAll instead of querySelector.

container
      .querySelectorAll('div[tabindex]').forEach(eachAccordian => {
        expect(eachAccordian).toHaveAttribute('aria-expanded', 'false')
      })
Sign up to request clarification or add additional context in comments.

Comments

4

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!

3 Comments

Thank you for your response. Can you give me an example? How can i use queryAllBy in this example?
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/…
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...
0

It seems "getByRole" solves many querySelector requirements.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.