admin管理员组文章数量:1434907
I am using Cypress tool in one of my projects and I can find some element containing a text, say XYZ, using something like this -
myElement() {
return cy.get('span:contains("XYZ")');
}
. However, I want to make this method generic by passing this value XYZ as a parameter. I tried something like this but it did not work -
myElement(text) {
return cy.get('span:contains(text)');
}
Can somebody please tell how this can be achieved?
Thanks in Advance..!!
I am using Cypress tool in one of my projects and I can find some element containing a text, say XYZ, using something like this -
myElement() {
return cy.get('span:contains("XYZ")');
}
. However, I want to make this method generic by passing this value XYZ as a parameter. I tried something like this but it did not work -
myElement(text) {
return cy.get('span:contains(text)');
}
Can somebody please tell how this can be achieved?
Thanks in Advance..!!
Share Improve this question edited Apr 14, 2021 at 13:02 user14783414 asked Apr 7, 2021 at 16:01 Akshay KaneAkshay Kane 2511 gold badge4 silver badges4 bronze badges2 Answers
Reset to default 2The way to use a parameter inside the function in the selector string is with Template literals.
Use back-ticks to create the selector string
function myElement(text) {
const selector = `span:contains(${text})`
return cy.get(selector);
}
or shorter
function myElement(text) {
return cy.get(`span:contains(${text})`);
}
or custom mand
Cypress.Commands.add('findElementWithText', (text) => {
cy.get(`span:contains(${text})`);
})
or using Cypress contains()
does not need template literals
Cypress.Commands.add('findElementWithText', (text) => {
cy.contains('span', text);
})
You can use Cypress custom mand to achieve this. Go to cypress/support/mands.js
and write:
Cypress.Commands.add('findElementWithText', (text) => {
cy.get(`span:contains(${text})`);
})
In your tests you can write:
cy.findElementWithText('randomText1')
cy.findElementWithText('randomText2')
本文标签: javascriptHow to pass the text as a parameter in cypress get commandStack Overflow
版权声明:本文标题:javascript - How to pass the text as a parameter in cypress get command - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745596693a2665524.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论