Skip to content Skip to sidebar Skip to footer

Cypress: Set Attribute Value

I have just started exploring Cypress and came across such a problem: is it possible to select a concrete attribute and change its value like in Selenium with the help of Javascrip

Solution 1:

Yes. Anything you can do in JavaScript is possible within Cypress tests. For the html above, you could do this within Cypress using .invoke():

cy.get('input[test]')
  .invoke('attr', 'test', 'my new value')
  .should('have.attr', 'test', 'my new value')

Cypress uses jQuery under the hood, so you can invoke any function in jQuery like this. You could alternatively use plain JavaScript after yielding the input using .then():

cy.get('input[test]').then(function($input){
    $input[0].setAttribute('test', 'my new value')
  })
  .should('have.attr', 'test', 'my new value')

Solution 2:

While Jennifer's answer actually works for most of the input elements, there is an exception especially when the application only takes the input value on input/change event as invoke will not trigger the event.

I had such experience and the below code worked for me.

In 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)
    })
  })

And in Tests:

   cy.get('[data-test="voy-lat-long-input"]')
        .then(input => cy.inputChange(input, Longtitude))

Solution 3:

You can try with this

cy.get('.class/#id').type('type your new value', { force: true });

Post a Comment for "Cypress: Set Attribute Value"