React testing library: how to getByRole on custom role
Asked Answered
P

2

4

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

Psychodiagnostics answered 12/4, 2022 at 23:0 Comment(0)
O
5

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');
Otolith answered 12/4, 2022 at 23:10 Comment(1)
thx for the reply, i just feel this is a such basic feature, wish RTL can add it. – Psychodiagnostics
T
0

If your goal is to use a getBy query that effectively asserts that this button and attribute pair exists, you may be able to query by the generic button role, then assert the disabled state:

expect(screen.getByRole("button")).toHaveAttribute("aria-pressed", "true");

or by text:

expect(screen.getByText("πŸ‘")).toHaveAttribute("aria-pressed", "true");

If the attribute is the only thing that makes it unique, then you may need to resort to a non-recommended approach such as a test id or the native DOM:

const {container} = render(<MyComponent1 />);
const el = container.querySelector(`button[aria-pressed="true"]`);
expect(el).toBeInTheDocument(); // with jest-dom
expect(el).not.toBeNull(); // without jest-dom; not a very clear error message

See also How to fetch element with 'name' attribute in react-testing-library and jest-dom #144.

Threadgill answered 15/12, 2022 at 19:17 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.