vendredi 17 juillet 2020

How to get element by proximity to another element in React Testing Library

I've been trying to write some tests using React Testing Library and following their guiding principles, in that the tests should test the application components in the way the user would use it.

I have an component that renders a list of objects with several fields about each, resulting in a DOM like this:

<div>
  <h1>Fluffy</h1>
  <h2>Cat</h2>
  <span>3 years old</span>
</div>
<div>
  <h1>Oscar</h1>
  <h2>Cat</h2>
  <span>2 years old</span>
</div>
<div>
  <h1>Charlie</h1>
  <h2>Dog</h2>
  <span>3 years old</span>
</div>

I would like to assert that each object is rendered correctly with the relevant fields, but I can't see how to do this using React Testing Library. So far I have:

it('renders the animal names, species, and ages', () => {
  render(<MyAnimalsComponent />)

  const fluffyName = screen.getByRole('heading', { name: 'Fluffy' })
  expect(fluffyName).toBeInTheDocument()

  // The problem here is that there are multiple headings with the name "Cat" (Fluffy and Oscar) and I have no way of checking that the one that is returned is actually the one for Fluffy.
  const fluffySpecies = screen.getByRole('heading', { name: 'Cat' })
  expect(fluffySpecies).toBeInTheDocument()

  // Likewise, the age "3 years old" is rendered for both Fluffy and Charlie. How do I make sure I get the one that is rendered in the same container as Fluffy's name?
  const fluffyAge = screen.getByRole('heading', { name: '3 years old' })
  expect(fluffyAge).toBeInTheDocument()
})

Is there any way to use the query methods in React Testing Library to only find elements with a common parent to another element? Or a way to get the parent of an element and then only find elements that are children of that element?

What is the best way to accomplish this while still following the guiding principles of React Testing Library?

Aucun commentaire:

Enregistrer un commentaire