.each() method, arrays and objects initialization #14960
-
Hello, I have noticed that when I use the .each(){} to initialize an array or object, I can print the array/object and see that it has all its elements/properties set outside of the construct. However, when I try to access a single element of that array or property of the object, they are undefined. I am trying to figure out what's happening; I guessed that the .each() in cypress would work like javascript .foreach(). I need some help here. const test = {} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Browser But this is only because it printed the object. When it prints a primitive value like a string, it cannot change it later, thus In your example the correct code would put const test = {}
cy.get('tbody > tr').each(($el, index, $list) => {
test.fname = 'Jane'
test.lname = 'Doe'
})
.then(() => {
console.log(test)
console.log(test.fname)
}) Read https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous to see more examples of executing asynchronous commands |
Beta Was this translation helpful? Give feedback.
Browser
console.log
method is "live", if the object is changed later, it shows the updated values. Thusconsole.log(test)
will show at first{}
then when the asynchronous Cypress commands finish will switch to showing{ fname: 'Jane', lname: 'Doe' }
.But this is only because it printed the object. When it prints a primitive value like a string, it cannot change it later, thus
console.log(test.fname)
prints undefined and never changes.In your example the correct code would put
console.log
statements into.then
callbaco so they execute AFTER.each
completes