Search code examples
javascriptloopsinputcypressinvoke

Cypress - Storing input values as alias and compare previous and current values


I want to store the values of all inputs via alias then after after changing the data get the current values and compare previous and current alias to each other.

My actions: First, getting all input values

for (let i = 0; i < 5; i++) {
        cy.get('.input').eq(i).invoke('val').then(val => cy.log(val)).as(`previous${i}`);
      }

Second, changing the data by selecting instance in dropdown

cy.get('.select').select(1);

Third, getting the current all input values

for (let i = 0; i < 5; i++) {
        cy.get('.input').eq(i).invoke('val').then(val => cy.log(val )).as(`current${i}`);
      }

Then I have created a method to compare.

for (let i = 0; i < 5; i++) {
        instanceConf.verifyingInputChanging(`@previous${i}`, `@current${i}`);
}

the method itself:

verifyingInputChanging(prevAlias, currenAlias){
    cy.get(prevAlias).then((prev_content) => {
      cy.get(currenAlias).then((cur_content) => {
        expect(cur_content).to.not.eq(prev_content)
      })
    })
  }

Unfortunately, it does not work to compare the input values. How to handle that?


Solution

  • This issue is coming from your attached .then() statements where you are cy.logging the values. If you remove those functions, then the test should run as expected.

    Why? When using the callback shorthand without an explicit return, you end up returning the function that is called within your .then(), and not the variable val. So your aliased "value" is null, as that is the yielded value of cy.log(val).

    If you need to cy.log the value, you'll have to return the entire statement, along with a separate then that yields the value. Otherwise, I'd recommend just removing the .then() entirely.

    // removing .then()
    for (let i = 0; i < 5; i++) {
          cy.wrap(i)
            .as(`prev${i}`);
        }
    
    // returning the `.then()`'d value
    for (let i = 0; i < 5; i++) {
          cy.wrap(i)
            .then((val) => {
              return cy.log(val).then(() => {
                return val;
              });
            })
            .as(`previous${i}`);
        }