'React testing library: how to getByRole on custom role

I have a component <MyComponent1> which

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

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



Solution 1:[1]

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');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mustafa