0

I'm going to run automation testing on a website using react Styled-Components. As styled component changing the CSS selectors frequently, my question is: What's an alternative to select an element contains a dynamic CSS style generated by Styled-Component?

I've used X-path, but not all elements are good candidate for x-path

Mmat
  • 1
  • 4

1 Answers1

2

Here is my solution. Hope it help you.

1. Use HTML5 attribute like data-testid, or data-what-ever-you-like

For example: (view 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;
`;

// A new component based on Button, but with some override 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. Use xpath to query your component:

$x("//div[@data-testid='myContainer']") 

$x("//div[@data-testid='myContainer']/button[@data-testid='tomatoButton']") 
anhquan
  • 1,338
  • 14
  • 21