首页 > 解决方案 > Cypress.io:如何创建有助于根据输入选择不同 DOM 元素的函数

问题描述

我知道您不能分配或使用任何 Cypress 命令的返回值,但是,我希望能够编写一个实用函数,允许我选择我希望的任何 DOM 元素,而不必每次都显式地写入 DOM 选择器因为我的所有测试的关键值都是相同的。

我的意思的一个例子是这样的:

<div data-e2e="one-div-element">
<div data-e2e="second-div-element>
<div data-e2e="third-div-element>
<div data-e2e="fourth-div-element>

我希望能够做允许的等价物:

const getByE2EID = (id) => cy.get('[data-e2e="${id}"]') // <--- (this of course, would be interpolated)

然后我就可以编写如下测试:

getByE2EID('third-div-element') // <--- and then I'd have the third div

我试图避免这样做:

cy.get('[data-e2e="first-div-element"]')

每次我想抓取一个 DOM 元素,因为它最终是......

cy.get('[data-e2e="first-div-element"]')
cy.get('[data-e2e="second-div-element"]')
cy.get('[data-e2e="third-div-element"]')
cy.get('[data-e2e="fourth-div-element"]')

一遍又一遍。

标签: javascriptcypress

解决方案


谢谢大家的帮助!根据您的建议,我能够翻译我需要在 Cypress.io 中编写的内容以使这个想法发挥作用,最终将其写入commands.js支持目录中的文件中:

Cypress.Commands.add('getDataE2EID', function (id) {
  return cy.get(`[data-e2e="${id}"]`)
})

cy.getDataE2EID('first-div-element')<--- 会给我第一个 div

现在,我可以有一个自定义的 cypress 函数,它允许我在键是“data-e2e”的地方传递我想要的任何值。


推荐阅读