使用 Protractor 在 Reactjs 非 angular 站点的 Span 标签内定位元素

Locating element inside Span tag in Reactjs non angular site using Protractor

我需要点击 span 标签内的 "login",代码如下所示

<div data-reactroot>
<div class "ant-dropdown ant-dropdown-placement-bottomRight ant-dropdown-hidden" style="left 632.234px; top 65px;">
<ul class="ant-dropdown-menu ant-dropdown-menu-light ant-dropdown-menu-root ant-dropdown-menu-vertical" role="menu" style="border" 1px solid rgba(0, 0, 0, 0.23);">
<li class="ant-dropdown-menu-item" role="menuitem">...</li>
<li class=" ant-dropdown-menu-item-divider"></li>
<li class="ant-dropdown-menu-item" role="menuitem">...</li>
            <span>Login</span>
</li>

https://i.stack.imgur.com/qDt4z.png

我尝试使用下面的代码,它不起作用:

browser.driver.findElement(by.cssContainingText('ant-dropdown-menu-item', 'Login'))

我收到一条错误消息,如下所示:

Message: 
Failed: Invalid locator
Stack:
TypeError: Invalid locator

试试看:

browser.driver.findElement(by.cssContainingText('.ant-dropdown-menu-item', 'Login'))

在 css 选择器中 class 需要有 ..

编辑: browser.driver.findElement(by.css('.ant-dropdown-menu-item > span'))

现在可以使用了,我尝试使用下面的代码

element(by.xpath("//span[. = 'Login']")).click();

ReactJS 测试变得更加简单 protractor-react-selector

protractor-react-selector 是一个轻量级插件,可帮助您使用道具和状态在您的 REACT 应用程序中定位 Web 元素。

您需要使用

安装插件
npm i -D protractor-react-selector

然后,您需要将插件添加到配置文件中:

exports.config = {
  // ... the rest of your config
  plugins: [
    {
      package: 'protractor-react-selector'
    }
  ]
}

然后,在 beforeAll`` hook or inside anonPrepare``` 挂钩中,等待 React 加载到您的应用程序中,如:

beforeAll(() => {
   await browser.get('http://localhost:3000/myApp')
   await browser.waitForReact()
})

然后你可以使用element(by.react)来获取反应元素。

const myElement = element(
  by.react('MyComponent', { someBooleanProp: true }, { someBooleanState: true })
)

myElement.click();

为了测试 React 元素,您不应依赖 HTML DOM 结构,因为大多数开发人员使用 material 创建动态 HTML 运行时的工具。

要查找更多示例,请访问这些 tests

可以在此处找到完整的 blog