Reputation: 4173
I want to store an array of strings taken from a page using cypress.
so far I have:
cy.get(".product-name").each(($el) => {
let text = $el.text();
cy.request("POST", "http://localhost:3000/sale-items", {
text
});
cy.wait(1000);
});
As you can see I am having to make separate requests for every item. But I want to store the entire array somehow, and then make one request.
I have read this page on variables and aliases but feel no closer to achieving what I want.
How to store an array of items generated from using Cypress commands?
Upvotes: 3
Views: 19099
Reputation: 308
function getProductName() {
let countProducts
cy.get('.product-name')
.then((elements) => {
countProducts = elements;
})
return countProducts
}
Cypress.Commands.add('getProductName', getProductName)
To invoke the method from any test:
cy.getProductName().then(element => {
cy.log(`Product names are: ${element.text()} `)
})
Upvotes: 0
Reputation: 8896
cypress provide .each($elem, index, $list) method to iterate each element of the array.
cy.get(".product-name").each(($els, index, $list) => {
// $list itself is collection of element
// $elem is each element of array
// index is postion of element in array
});
Upvotes: 3
Reputation:
You can use .then()
instead of .each()
to retrieve all elements classed 'product-name'. The parameter is an iterable collection that can be converted to an array.
Ref Array.from
cy.get(".product-name").then(($els) => {
const texts = Array.from($els, el => el.innerText);
cy.request("POST", "http://localhost:3000/sale-items", {
texts
});
cy.wait(1000);
});
Upvotes: 3