我刚开始探索Cypress,遇到了这样一个问题:是否可以像Selenium中使用JavascriptExecutor
一样选择具体的属性并更改它的值?例如,让我们来看一下这个简单的代码片段:
input id="mapsearch" type="textbox" class="form-control" name="address" test=""
我可以获取测试属性并赋予自己的值吗?
我刚开始探索Cypress,遇到了这样一个问题:是否可以像Selenium中使用JavascriptExecutor
一样选择具体的属性并更改它的值?例如,让我们来看一下这个简单的代码片段:
input id="mapsearch" type="textbox" class="form-control" name="address" test=""
我可以获取测试属性并赋予自己的值吗?
是的。在 Cypress 测试中,您可以做到 JavaScript 可以做的任何事情。对于上面的 HTML,您可以使用 .invoke()
在 Cypress 中完成:
cy.get('input[test]')
.invoke('attr', 'test', 'my new value')
.should('have.attr', 'test', 'my new value')
Cypress在内部使用jQuery,因此您可以像这样调用jQuery中的任何函数。您还可以在使用.then()
后,使用纯JavaScript来操作输入:
cy.get('input[test]').then(function($input){
$input[0].setAttribute('test', 'my new value')
})
.should('have.attr', 'test', 'my new value')
Jennifer的回答适用于大多数输入元素,但在应用程序仅在上获取输入值时,存在一个例外,因为调用不会触发事件。
我有这样的经历,下面的代码对我有效。
在Commands.js中:
Cypress.Commands.add('inputChange', (input, value) => {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
'value'
).set
const changeInputValue = inputToChange => newValue => {
nativeInputValueSetter.call(inputToChange[0], newValue)
inputToChange[0].dispatchEvent(new Event('input', {
newValue,
bubbles: true,
composed: true
}))
}
return cy.get(input).then(input => {
changeInputValue(input)(value)
})
})
在测试中:
cy.get('[data-test="voy-lat-long-input"]')
.then(input => cy.inputChange(input, Longtitude))
.invoke()
后面添加.trigger('change')
来触发更改事件(如果需要输入事件,则使用.trigger('input')
)。 - Fody你可以尝试使用这个方法
cy.get('.class/#id').type('type your new value', { force: true });