Deane Kane
Deane Kane

Reputation: 151

Array.toString returns empty outside of loop

I am new to JavaScript so sorry if this is a stupid question or duplicate.

I have an Array and Loop, within the loop I log each time and it will return something along the lines of: A1, A1 A2, A1 A2 A3... so on and so forth until it completes the loop.

At the end I attempt to log the final Array value and it returns empty.

Any ideas?

  var testArray: any = new Array();
  var test: any;

  cy
    .get('element')
    .each(function ($el, index) {
      test= $el.text();
      testArray.push(test);
      cy.log(testArray.toString())
    })
  cy.log(testArray.toString())

Thanks

Upvotes: 1

Views: 490

Answers (1)

Leandro Matilla
Leandro Matilla

Reputation: 1011

You may use .then(); quoting from the cypress documentation for .then():

.then() is modeled identically to the way Promises work in JavaScript. Whatever is returned from the callback function becomes the new subject and will flow into the next command (with the exception of undefined).

Try something like this:

var testArray: any[] = new Array();

cy
    .get('element')
    .each(($el) => {
        testArray.push($el.text());
        cy.log(testArray.toString());
    ).then(() => cy.log(testArray.toString())
});

Upvotes: 2

Related Questions