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')
?
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')
?
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');
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.
© 2022 - 2024 β McMap. All rights reserved.