Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library: how to getByRole on custom role

I have a component <MyComponent1> which returns:

return (<MyComponent2> <button aria-pressed="true">👍</button> </MyComponent2>);

Now in my unit test for MyComponent1, is there a way I can do screen.getByRole('MyComponent2')?

like image 790
user3552178 Avatar asked Sep 01 '25 20:09

user3552178


1 Answers

No, it's not possible to specify a custom role; the roles are predefined.

That being said, if what's returned ultimately is a button then you can use 'button' as the role as it is a valid role.

If you want to target MyComponent2 specifically you can add a test-id to it and use getByTestId.

// MyComponent1.tsx
const MyComponent1 = () => 
  <MyComponent2 data-testid="Comp2"><button aria-pressed="true">👍</button></MyComponent2>


// MyComponent1.spec.tsx
const myComponent2 = screen.getByTestId('Comp2');
like image 119
M Mansour Avatar answered Sep 03 '25 09:09

M Mansour