最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to pass the text as a parameter in cypress get command - Stack Overflow

matteradmin6PV0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 2

The 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')
Post a comment

comment list (0)

  1. No comments so far