How to Select a Specific Point on a Vuetify <v-slider> with Cypress

Viewed 1038

I'm testing how my app reacts to a user clicking on a specific spot on a basic Vuetify <v-slider>. What is the best way to simulate this in a Cypress integration test?

For example, I can click on the middle of the <v-slider> with:

cy.get(#sliderID).find('input[role="slider"]').click()

However, i would like to click on a different spot of the <v-slider>. For instance, for a <v-slider> with a min value of 0 and a max value of 100, I would like to simulate a click on 25. How can I do this?

2 Answers

GMaiolo's answer is fundamentally correct.

In case it should be helpful to anyone else, here is a quick function I made (based on GMaiolo's answer) to click on a specific point of a Vuetify v-slider:

// example usage: clickVSlider('#selectID input[role="slider"]', 0.25)

const clickVSlider = (sliderSelector, percentFromLeft) => {
  const sliderWidth = Cypress.$(sliderSelector).width()
  const sliderHeight = Cypress.$(sliderSelector).height()
  const pixelsFromLeft = percentFromLeft * sliderWidth
  const pixelsFromTop = 0.5 * sliderHeight
  cy.get(sliderSelector).click(pixelsFromLeft, pixelsFromTop)
}

Or, perhaps it is preferable to use a more 'composable function' style:

// example usage: cy.get('#selectID input[role="slider"]').then(clickVSlider(0.25))

const clickVSlider = percentFromLeft => subject => {
  const sliderWidth = subject.width()
  const sliderHeight = subject.height()
  const pixelsFromLeft = percentFromLeft * sliderWidth
  const pixelsFromTop = 0.5 * sliderHeight
  cy.wrap(subject).click(pixelsFromLeft, pixelsFromTop)
}

Alternatively, we can create a Cypress custom command, although we want to make sure we don't get too overzealous in the usage of custom commands:

// cypress/support/commands.js
// example usage: cy.get('#selectID input[role="slider"]').clickVSlider(0.25)

Cypress.Commands.add('clickVSlider', {prevSubject: true}, (subject, percentFromLeft) => {
  const sliderWidth = subject.width()
  const sliderHeight = subject.height()
  const pixelsFromLeft = percentFromLeft * sliderWidth
  const pixelsFromTop = 0.5 * sliderHeight
  cy.wrap(subject).click(pixelsFromLeft, pixelsFromTop)
})

Cypress accepts coordinates for click events

You should be able to calculate the exact spot you'd like to click on by using the width of the element and the properties of the slider component (steps, max value and min value)

Related