'Cypress: how to split numbers found in divs?
I have a test that is going into an elements span > div but there are two of them so when I run the test it concatenates both of them into one number 13,900879,210. I need it to give me them separately to compare them such as 13,900 and 879,210. Here is my code. Can anyone help with this?
cy.get(`div[id]=2`).find('span').find('div').invoke('text').then((nums) => {
cy.log(nums) // 13,900879,210
})
Solution 1:[1]
You can't really split the combined text (unless you know how many characters in each).
You can get the texts individually,
cy.get(`div[id="2"]`).find('span').find('div')
.then($divs => {
const nums = [...$divs].map(div => div.innerText)
cy.log(nums) // ['13,900', '879,210']
})
where
$divsis a jQuery object holding both divs[...$divs]converts the jQuery object to an array of (raw) elements.map(div => +div.innerText)maps elements into their text values
To work with integers, add a + to the map
cy.get(`div[id="2"]`).find('span').find('div')
.then($divs => [...$divs].map(div => +div.innerText))
.should('deep.eq', [13900, 879210])
Solution 2:[2]
You can use Cypress' .each() function to iterate through each element yielded.
cy.get(`div[id]=2`).find('span').find('div').each(($el) => {
// $el is a JQuery element, so we can use JQuery functions like `.text()`
cy.log($el.text());
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | agoff |
