Home > Blockchain >  Cypress How do tick check boxes with no unique selectors
Cypress How do tick check boxes with no unique selectors

Time:07-02

I am trying to select/tick checkboxes with no obvious selectors but a class name which is shared by all the checkboxes on the page.

Can someone please share how I can test these elements with no selectors.

I am testing a search engine.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

CodePudding user response:

Then You can directly use the text to find the locator and click it, something like:

cy.contains('Tool').click()

For the search button, you have the aria-label tag, you can use that directly:

cy.get('input[aria-label*="main-search-box"]').type('text')

CodePudding user response:

I believe it goes against cypress' best practices to try and select any element other than using data-cy="add-unique-id-here" selector. The docs suggest that using CSS-style selectors is brittle, and may cause tests to fail in the future when you update your code. By using data-* selectors, you can gaurantee you're always selecting what you need.

Here's the link for the cypress docs: Example code from cypress docs

In your case, adding <span data-cy="descriptive-checkbox-name"> <svg>...</svg> </span> to your html

and cy.get('[data-cy=descriptive-checkbox-name]') to your cypress testing file, should do the trick.

CodePudding user response:

Given the text for the checkboxes are unique, you can use cy.contains()

// 'Under 6 min' checkbox
cy.contains('span', 'Under 6 min')

// 'Tool' checkbox
cy.contains('span', 'Tool')

As for the search box, it will get a bit trickier. If it is the only search box that is visible on the page you can do the following.

cy.get('input[type=text][placeholder]')
  .filter(':visible')
  • Related