赛普拉斯单击元素的ID / XPATH /名称?

时间:2019-07-04 11:02:18

标签: automation cypress

我想单击XPATH / ID上的元素,而不是默认的赛普拉斯定位器,这可能吗?

在硒中,我可以通过XPATH使用find元素,例如: d.findElement(By.id(“ category”))。click();

在Cypress中,它像: cy.get('#hdtb-msb-vis>:nth-​​child(3)> .category')。click()

我可以按ID单击吗? 硒看起来更好!

d.findElement(By.id("category")).click();

VS

cy.get('#hdtb-msb-vis > :nth-child(3) > .category').click()

6 个答案:

答案 0 :(得分:2)

如果要在赛普拉斯中使用xpath,有两件事要做:-

  1. 在文件夹“ YourProject”->“ cypress”->“ support”下的文件“ index.js”中,添加条目“ require('cypress-xpath')”
  2. 在文件夹“ YourProject”->“配置”->“ docker”下的文件“ Dockerfile.cypress”中,添加条目“ RUN npm install cypress-xpath”

仅需使用所有xpath函数来唯一标识cypress测试中的所有元素。 我个人更喜欢使用xpath,因为这可以让我对UI元素进行更多控制。希望这将使使用柏树的生活更加轻松。

答案 1 :(得分:1)

在赛普拉斯中,它的工作方式如下:

cy.get('button[id="category"]').click()

请注意,这里我只是以按钮为例,您应该将其替换为元素标签:div,select,textarea等...

答案 2 :(得分:0)

#hdtb-msb-vis是ID选择器,而.category是类选择器。但是您应该只能通过类选择器进行选择

cy.get('.category')
  .click()

但是如果该类不是唯一的,则可以通过ID单击该类,然后单击该类:

cy.get('#hdtb-msb-vis')
  .find('.category')
  .click()

答案 3 :(得分:0)

我认为,可以按照赛普拉斯网站的建议添加一个plug-in,请参考以下链接https://docs.cypress.io/plugins/#content。如果您参考自定义命令部分,您会看到cypress-xpath,它将带您到以下github链接   https://github.com/cypress-io/cypress-xpath

npm install -D cypress-xpath

然后将其包含在项目的cypress / support / index.js中

require('cypress-xpath')

下面给出了示例用法:

it('finds list items', () => {
  cy.xpath('//ul[@class="todo-list"]//li')
    .should('have.length', 3)
})

请在安装插件并更新support/index.js文件后尝试。

答案 4 :(得分:0)

第一个问题包含两个不同的选择器,第一个(硒)查找id类别,第二个选择类类别。

事实上:

d.findElement(By.id("category")).click();
==
cy.get('#category').click()

是的,您可以通过其ID选择一个元素!

  

如果(但我不认为)您希望其他人来选择您的元素,则寻找jquery选择器(jquery is exposed in cypress

答案 5 :(得分:0)

执行npm install -D cypress-xpath

如果您使用打字稿。在 cypress/support/index.d.ts 中添加一个文件

添加 import './commands'; import '../../node_modules/cypress-xpath';

"types": ["cypress", "cypress-xpath"] in tsconfig.json

还要在 index.js 文件中添加 import '../../node_modules/cypress-xpath

相关问题