Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

424
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!