Here is the solution I came up with. Hopefully, it proves helpful for you.
1. Incorporate HTML5 attributes such as data-testid, or create custom ones
For instance: (check it out live on codesandbox)
import React from "react";
import styled, { css } from "styled-components";
const BorderBox = styled.div`
text-align: center;
border: 1px solid #cacaca;
`;
const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
// Customize Button component with new styles
const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`;
export const MyContainer = React.memo(props => {
return (
<BorderBox data-testid="myContainer">
<TomatoButton data-testid="tomatoButton">Tomato Button</TomatoButton>
<Button data-testid="normalButton">Normal Button </Button>
</BorderBox>
);
});
2. Utilize xpath to query your components:
$x("//div[@data-testid='myContainer']")
$x("//div[@data-testid='myContainer']/button[@data-testid='tomatoButton']")