0

In the below code snippet,

function retreive_data_from_UI() {
    let arr_rows = [];
    cy.get(constants.cssCustomerWoListViewTable).children().each(($rows, ind) => {
        arr_rows.push($rows.text());
        cy.log(ind);
        cy.log(arr_rows[ind]);
    });
    cy.wait(1000);
    for(var i = 0; i < 5; i++){
        // I tried both separately pop() and accessing by index
        cy.log(arr_rows.pop());
        // or
        cy.log(arr_rows[i]); 
    }
    return arr_rows;
}

the value for arr_rows[ind] is printed within cy.get().children().each(() => {}) block but not in the for loop that follows it. Below is the output

Output

Can anyone point out where I went wrong ? I am using cypress for writing frontend tests.

jo_va
  • 13,504
  • 3
  • 23
  • 47
  • Generally speaking, you need to build a custom command instead of a JS function. Put a `console.log()` after `arr_rows.push()` and another inside `for(var i = 0; i < 5; i++){`, you will see the order of execution. –  Feb 05 '19 at 02:06

2 Answers2

1

It could be, because you are declaring let arr_rows, meaning a block scope. You are trying to fill it in an anonymous function, which has its own scope and therefore its own arr_rows.

Declare arr_rows with var arr_rows = [] and it should work.

See here for more details.

Musti
  • 139
  • 1
  • 9
1

I resolved this by using the suggestions in the (Return from a promise then()) :

Created and returned a Promise. This way I was able to use the resolved value (this.result) in another function too.

function retreive_data_from_UI(){
  var result = [];
  return new Promise(function(resolve){
    cy.get(constants.cssCustomerWoListViewTable).children().each(($rows, ind) => {
      result.push($rows.text());
    }).then(function(){
      this.result = result;
      for(var i = 0; i < 5; i++){
        cy.log(this.result[i]) // content printed here
      }
      resolve(this.result)
    });
  });
} 

Using the value of this.result in another function

it('Test WO Sorting Ascending', () => {
    cy.get(constants.btnLmsWOSortAsc)
    .click()
    .then(function() {
      retreive_data_from_UI()
      .then(function(result){
        for(var i = 0; i < 5; i++){
          cy.log(result[i]); // content printed properly here too
        }
      });
    });
});