Home > other >  How to get Component by dynamic testid using React Testing Library
How to get Component by dynamic testid using React Testing Library

Time:11-09

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?

CodePudding user response:

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)
  } 
});
  • Related