Search code examples
javascripttestingcypresse2e-testing

cypress invoke('removeAttr', 'target') not working


This is my cypress code:

 cy.get(`${sitestovisit.searchBoxFormID} > form`)
   .should('have.attr', 'target')<br>
   .invoke('removeAttr', 'target')

sitestovisit.searchBoxFormId contains data from JSON and its working properly but it shows that there is a target attribute in form, but when I tried to remove it, it is not working.

and when i replace above code with:

 cy.get('#booking_search > form')
  .invoke('removeAttr', 'target')

it works fine, what's the problem? i can't use directly cause I need it in loop Here's the output


Solution

  • Is failing because you have this assertion .should('have.attr', 'target') before this invocation .invoke('removeAttr', 'target').

    The .should('have.attr', 'target') changes the subject from the element to the attribute, but .invoke('removeAttr', 'target') requires the subject to be the element in order to work.

    this will work

     cy.get(`${sitestovisit.searchBoxFormID} > form`)
       .invoke('removeAttr', 'target')
    

    And.. if you need to see if the target attribute exist before deleting it I would do this.

      cy
          .get(`${sitestovisit.searchBoxFormID} > form`)
          .should('have.attr', 'target')
    
      cy
           .get(`${sitestovisit.searchBoxFormID} > form`)
           .invoke('removeAttr', 'target')