I have a HTML code like this
<ul >
<li>Home</li>
<li>About</li>
<ul>
<li>About1</li>
<li>About2</li>
<li>About3</li>
</ul>
<li>Contact</li>
<li>Links</li>
</ul>
What i want to achieve is to get all the text of li's and convert it to array so that i can use each array for comparison to other values. but the twist is the li's are constantly changing
So far i have this code on cypress
it('List to array', () => {
cy.get('*[class^="menu-main-nav-container"]').eq(0).then($text => {
const text = $text.text().toString().slice('')
cy.log(text[0])
})
})
It just log the text 'H' for now but i want to achieve is text = ["Home", "About", "Contact", Links" ] so that i can compose text[0] that i can use
I'm so stuck right now
CodePudding user response:
One way, you can take advantage of Cypress selecting multiple elements, then convert elements to texts
cy.get('.menu-main-nav-container')
.find('li') // gets all li including sub-menu ones!
.then($els => {
return Array.from($els).map(el => el.innerText)
})
.should('deep.eq', ['Home', 'About', 'About1', 'About2', 'About3', 'Contact', 'Links'])
or top-level only
cy.get('.menu-main-nav-container')
.children('li') // gets main menu options
.then($els => {
return Array.from($els).map(el => el.innerText)
})
.should('deep.eq', ['Home', 'About', 'Contact', 'Links'])
CodePudding user response:
You can do something like this:
it('List to array', () => {
var list = []
cy.get('ul[] > li')
.each(($ele) => {
list.push($ele.text().trim())
})
.then(() => {
cy.log(list[0]) //prints Home
})
})
Or, you can do also something like this:
var list = []
cy.get('ul[] > li')
.then(($ele) => {
const list = Array.from($ele, (el) => el.innerText)
})
.then(() => {
cy.log(list[0]) //prints Home
})
