Search code examples
textcypress

How to assert that a form field contains some text, regardless of what the text is in Cypress?


A little background on this is:

Let us say I have a form with "n" input fields.

I am testing whether entering data into a key form field would auto-populate the other (n-1) fields. At this point I am not worried about what data is being auto-populated, only whether it is being populated.

How do I do this in Cypress?


Solution

  • Here's what I think is a reproducible example

    <body>
      <form>
        <input id="key" onblur="autofill()" />
        <input id="1" />
        <input id="2" />
        <input id="3" />
      </form>
    
      <script>
        function autofill() {
          [1,2,3].forEach(id => {
            const input = document.getElementById(id)
            input.value = "Value " + id
          })
        }
      </script>
    </body>
    

    and here's the test

    cy.get('#key').type('the key').blur()  
    
    cy.get('input:not(#key)')
      .each($nonKeyInput => {
        cy.wrap($nonKeyInput)
          .invoke('val')
          .should('not.be.empty')  // passes
      })
    

    Make an error in the app

    [1,2].forEach(id => {
    

    and the test fails.