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

426
Visualizações
How to get Component by dynamic testid using React Testing Library

Currently I'm working on unit tests creation for my project, the part of code I'm writing tests looks like:

  {errors.map(error => (
         <li
          data-testid={`${error.key}-error-item`}
          key={error.key}
          className={error.className}
        >
          <Container>{error.message}</Container>
        </li>
   ))}

I use a dynamic `data-tested key to get this element within tests. My test looks like this:

...
expect(screen.queryAllByTestId(`${error.key}-error-item`).length).toEqual(1)
...

But this test fails, please tell me how can I get items by `dynamic data-tested property?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to iterate across the same errors you pass into (or expect to receive in your component. For example the following component:

import React from 'react';


const MyComponent = ({errors}) => <div>

{errors.map(error => (
         <li
          data-testid={`${error.key}-error-item`}
          key={error.key}
          className={error.className}
        >
          <div>{error.message}</div>
        </li>
   ))}
</div>

export default MyComponent;

will pass the following test absolutely fine:

import { render, screen } from '@testing-library/react';
import MyComponent from './features/test-feature';

const ERRORS = [{key: 1, className: 'class1'}, {key: 2, className: 'class2'} ]

test('renders learn react link', () => {
  render(<MyComponent errors={ERRORS}/>);

  for(let error of ERRORS){
    expect(screen.queryAllByTestId(`${error.key}-error-item`).length).toEqual(1)
  } 
});
about 4 years ago · Juan Pablo Isaza Relatório
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