Here is the program piece where you can see that:
- var likes = [] is defined before cy.get:
- likes is populated inside the each () method I want to sort likes array as in the below code. But that is not getting sorted. cy is cypress The problem is that I like to sort this likes array outside cy.get(..).each() as next instruction not inside. But that is not working and I have no clue as to why. Please could you help in here ?
var likes = []
cy.get('.blogs').each(($el, index) => {
const bcy = cy.wrap($el)
bcy.get('#viewBlog').click()
const like = Math.floor(Math.random() * 10)
likes[index] = like
for(let i=like;i--; )
bcy.get('.blogsDetail').eq(index).contains('likes').click()
})
likes.sort((a, b) => b - a) //Sorting at this place doesn't work
CodePudding user response:
Cypress commands are asynchronous. To sort the array after the each
command, you have to use a then
callback:
var likes = []
cy.get('.blogs').each(($el, index) => {
const bcy = cy.wrap($el)
bcy.get('#viewBlog').click()
const like = Math.floor(Math.random() * 10)
likes[index] = like
for(let i=like;i--; )
bcy.get('.blogsDetail').eq(index).contains('likes').click()
}).then(() => {
likes.sort((a, b) => b - a)
})
Wheny you call the sort
method out of a then
, it's executed before any cypress command and you have an empty array at that moment. See it in debugger: