Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How to match a parent node based on the text of the child node in React Testing Library

I am trying to write some tests for two lists of users (users and members, identical markup, different semantic content) in React Testing Library. Details of each user are inside of a span element.

I have this DOM tree:

<div>
   <span>
      <div>
        <b>Text 1</b>
      </div>
      <div>
        <!-- other elements here -->
      </div>
   </span>
</div>
<div>
   <span>
      <div>
        <b>Text 2</b>
      </div>
      <div>
        <!-- other elements here -->
      </div>
   </span>
</div>
<div>
   <span>
      <div>
        <b>Text 3</b>
      </div>
      <div>
        <!-- other elements here -->
      </div>
   </span>
</div>

I want to match the span element (because it handles the onClick logic) based on the text inside the b child element (because it contains user's name and last name).

I tried doing it this way:

const getUsersLists = (doc) => ({
  usersList: doc.querySelector('.users-users-list'),
  membersList: doc.querySelector('.members-users-list'),
});

const getUser = (name, list) => (
  screen.findByText(name), { selector: 'span' }, { container: list })
);

test('users exist', () => {
  const { usersList } = getUsersLists(document); 

  const sampleUser = await getUser('Text 1', usersList);

  expect(sampleUser).toBeInTheDocument();
});

The problem:

Those matchers successfully find the Text 1 text if I remove the { selector: 'span' } options object from the getUser method. As soon as I tell RTL to look for a span element it can't find anything.

I also want to avoid any more document.querySelector and class / ID (including data-testid) references.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda