css - 将 Styled-Component 与 Selenium 定位器集成

标签 css reactjs selenium python-unittest styled-components

<分区>

我将使用 React Styled-Components 在网站上运行自动化测试。由于样式组件经常更改 CSS 选择器,我的问题是: 选择包含由 Styled-Component 生成的动态 CSS 样式的元素的替代方法是什么?

我使用了X-path,但并非所有元素都适合 x-path

最佳答案

这是我的解决方案。希望对你有帮助。

<强>1。使用 data-testid 或 data-what-ever-you-like 等 HTML5 属性

例如:(在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。使用 xpath 查询您的组件:

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

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

关于css - 将 Styled-Component 与 Selenium 定位器集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453643/

上一篇:javascript - 为什么延迟加载会重新定位背景图片?

下一篇:css - 如何删除 JS 计时器上数字周围的空格?

相关文章:

java - 无法解析类引用 org/openqa/selenium/WebDriver

php - 将 css li 添加到 php?

reactjs - 使用 Youtube Data API v3 时请求缺少有效的 API key

css - 带有绝对定位页面的粘性页脚

javascript - div 中的最后一个 span 改变了它的宽度

javascript - 向 FlatList 添加标题

python - 将 Winium (+ Selenium) 与 python 一起使用只允许我打开应用程序,但不会与之交互?

c# - 使用 Browser.Current 在 C# 中使用 Baseclass.Contrib.Specflow 调用浏览器

html - 如何为多个元素设置一张连续的背景图片

css - 如何将内容置于 td 元素的中心