Testing Library’s getByRole not working when element has extra markup

  javascript, jestjs, react-testing-library

I’m trying to test the following alert is displayed on a component:

<p role="alert">
  <strong>Name</strong> is there
</p>

Then, my test has this:

expect(screen.getByRole('alert', { name: /name is there/i })).toBeInTheDocument();

However, the test fails saying the element could not be find and it shows the alert role with an empty name:

alert:

Name "":

<p
  class="label"
  role="alert"
>
  <strong>
   Name
  </strong>
               
  is 
  there
</p>

Any ideas on what I’m doing wrong here?

Source: Ask Javascript Questions

LEAVE A COMMENT