I'm trying to get contact information through cypress and compare it with database. So I need to split the details and get Title, First Name, Last Name, Country... etc.
But the text contain in a single div and it has been separated using <br> tag.
Then I have tried to get the text as follows:
cy.xpath('element xpath').invoke('text').then((AddressLineText) => {
cy.log(AddressLineText);
});
Flowing is the invoked text and it has been connected the line texts without even a space. Due to that I'm unable to split by space or /n.
Bellow is the HTML structure:
<div class="address">
Mr. Test User
<br>
Testing Services Ltd
<br>
Britannia House
<br>
Rushmills
<br>
NN4 7YB, Northampton
<br>
Northamptonshire
<br>
United Kingdom
</div>
How to isolate each lines according to this scenario.
The <br> tags become newlines after text extract
cy.get('.address')
.invoke('text')
.then(text => text.split('\n')) // split by newline
.then(texts => texts.map(text => text.trim())) // trim whitespace
.then(texts => texts.filter(text => text)) // remove empty
.then(texts => {
console.log(texts)
})
})
prints
["Mr. Test User", "Testing Services Ltd", "Britannia House", "Rushmills", "NN4 7YB, Northampton", "Northamptonshire", "United Kingdom"]
Node.TEXT_NODE
Extracting the text nodes of the div is better if the content is more complicated.
.childNodes to get all <br> and texts within address <div><br>cy.get('.address')
.then($el => $el[0].childNodes)
.then(children => [...children].filter(child => child.nodeType === Node.TEXT_NODE))
.then(textNodes => textNodes.map(textNode => textNode.nodeValue.trim()))
.then(texts => {
console.log(texts)
})
prints
["Mr. Test User", "Testing Services Ltd", "Britannia House", "Rushmills", "NN4 7YB, Northampton", "Northamptonshire", "United Kingdom"]
You can use each() to get all your individual texts printed. One line for each text in the test runner logs.
cy.xpath('element xpath').each(($ele) => {
cy.log($ele.text());
});