javascript - 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"]')
一遍又一遍。
解决方案
谢谢大家的帮助!根据您的建议,我能够翻译我需要在 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”的地方传递我想要的任何值。
推荐阅读
- ruby-on-rails - 如何使用可选的部分返回默认值
- ubuntu-16.04 - Ubuntu 7z 开关不工作
- javascript - Highcharts:无法加载 Xaxis 上的所有值
- javascript - 从 JavaScript 中的字符串播放音频文件
- python - 使用 json 反序列化 sklearn 模型对象时为只读属性分配值
- c - 如何从函数返回 2 个数字
- ios - iOS CoreML mlmodel 文件自动生成模型类文件的 swift 版本
- python - 通过取列之间的平均值来合并 Pandas 中的两个数据框
- r - k 步中的最大排列 (R)
- python - 如何正确地将 kwargs 从 django 登录传递给 RedirectView 以重定向到用户配置文件?