无法使用箭头键移动滑块<输入类型= "range" >



我试图在这里实现一些测试,不能将我的逻辑应用到这个网站的输入范围:https://the-internet.herokuapp.com/horizontal_slider

这里是我的代码

it('and a slider is displayed, the slider is moved to a specific position', () =>{
cy.visit('/horizontal_slider')
// to achieve this, we need to know the attributes of the slider component
// min; max; value and step
// we need to move the slider using the keyboard (right arrow) to move the slider
// each type the key is pressed, the slider will move one value equal to the "step" attribute
const destiny = 1
const step = 0.5
const initialValue = 0
const stepsToReachDestiny = (destiny - initialValue) / step 
// now we repeat x times (stepsToReachDestiny) 
// the key press to reach the value
const keyboardCommandRepeated = '{rightArrow}'.repeat(stepsToReachDestiny)
// and call the function
cy.get('.sliderContainer > input').click()
cy.get('.sliderContainer > input').type(keyboardCommandRepeated)
// check the value in the slider
cy.get('.sliderContainer > span')
.should('have.value', destiny)
})

滑块就是不移动。Cypress文档说使用invoke()方法,但我宁愿避免看到滑动条被移动

这里有几件事。

范围输入不响应Cypress'.type('{rightArrow}'),但您可以使用Cypress -real-events.realType('{rightarrow}')代替。

注意rightarrow代替rightArrow

看一下源代码,有一个onchange事件处理程序来更新跨度。

<input type="range" min="0.0" max="5.0" step="0.5" value="0" onchange="showValue(this.value)">

要更改span,您需要触发此更改事件。

这意味着你不能重复rightarrow,每一步都需要单独触发更改事件。

最后,span有text而不是value

it('and a slider is displayed, the slider is moved to a specific position', () =>{
cy.visit('https://the-internet.herokuapp.com/horizontal_slider')
const destiny = 1
const step = 0.5
const initialValue = 0
const stepsToReachDestiny = (destiny - initialValue) / step 
cy.get('.sliderContainer > input').focus()    // use focus instead of click

// loop the steps so that we can trigger change event each step
Cypress._.times(stepsToReachDestiny, (i) => {
const expectedAtThisStep = (i+1) * step
cy.get('.sliderContainer > input').realType('{rightarrow}')
cy.get('.sliderContainer > input').trigger('change')
// check the internal value
cy.get('.sliderContainer > input')
.invoke('val').then(val => +val)  // get value text and convert to number
.should('eq', expectedAtThisStep)
// check the external span text
cy.get('.sliderContainer > span')
.should('have.text', expectedAtThisStep)
})
cy.get('.sliderContainer > span')
.should('have.text', destiny)
})

最新更新