1

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?

1 Answer 1

1

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)
  } 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.