'How to pass the text as a parameter in cypress get command

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..!!



Solution 1:[1]

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 command

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);
})

Solution 2:[2]

You can use Cypress custom command to achieve this. Go to cypress/support/commands.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')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 pico_prob