cypress-io / cypress

Fast, easy and reliable testing for anything that runs in a browser.
https://cypress.io
MIT License
47.02k stars 3.18k forks source link

data-cy selector in the playground #27165

Open muratkeremozcan opened 1 year ago

muratkeremozcan commented 1 year ago

What would you like?

We would love to have a cy.getByCy added (or any custom command) for data-cy attributes (or any custom data attributes) to the playground.

We use the playground religously for both e2e and ct. Usage of data-cy attributes are wide spread starting from the common component library to the applications, but we keep having to modify the value in our test code.

For example:

// copy paste from playground
cy.get('[data-cy="login-button"]')
// have to modify to our custom command
cy.getByCy('login-button')
Screenshot 2023-06-29 at 8 19 53 AM

Why is this needed?

Convenience when using the playground. Saving time on the manual labor of modifying the copy pasted value to our custom command has a high impact at scale. It also has implications for wider spread usage of the wizard.

Other

No response

lmiller1990 commented 1 year ago

Interesting idea -- there's no good way to "know" which custom command is most appropriate (same with get/contains - the user needs to choose).

The best thing that would be possible is allowing (or automatically) populating the dropdown with custom commands. Authors will still need to "tell" Studio how to construct a command. An example might be

Cypress.Commands.add('findByTestId', (id) => {
  return cy.get(`[data-testid=${id}]`)
}, {
  studio: (id) => {
    // look for element using jquery
    const $el = Cypress.$("[data-testid=${id}]")

    if ($el) {
      // found it. Return a string to write in the test generated by studio.
      return `cy.findByTestId("${id}")`
    }

    // did not find it - do nothing
    return null
  }
})

It would be useful for heavy users. We'd need to explore how practical this would be with larger, more complex custom commands.

Ideally, if this was popular, third party libraries (like Cypress Testing Library) would adopt it and ship studio construct logic with their selectors.