'How can I save part of a string in an alias using Cypress?

I'm trying to save just a number from a string I get from a paragraph but when I try to asign an alias to it and then check the value it returns undefined. I've tried a few solutions I found but none of those seem to work for me. These are two ways I tried (I tried another one similar to the second one but using split, had same result). The console.log inside of the 'then' doesn't show in the console, and when I try the alias after the code is when I get undefined.

    cy.get('p')
      .eq(1)
      .should('have.text', '/[0-9]+/g')
      .as('solNumber')

    cy.get('p')
      .eq(1)
      .invoke('text')
      .then((text)=>{
        var fullText = text;
        var pattern = /[0-9]+/g;
        var number = fullText.match(pattern);
        console.log(number);
      })
      .as('solNumber')


Solution 1:[1]

Please convert with + operator and return the numeric value if you want numeric type to be stored.

cy.get('p').eq(1)
  .invoke('text')
  .then(fullText => {
    const number = fullText.match(/[0-9]+/);
    return +number     // text to numeric
  })
  .as('solNumber')

cy.get('@solNumber')
  .should('eq', 42)    // numeric type
});

Solution 2:[2]

Running your 2nd code on this,

<p>21</p>
<p>42</p>

gives the correct outcome

cy.get('p')
  .eq(1)
  .invoke('text')
  .then((text)=>{
    var fullText = text;
    var pattern = /[0-9]+/g;
    var number = fullText.match(pattern);
    console.log(number);                    // logs 42
  })
  .as('solNumber')

cy.get('@solNumber')
  .should('eq', '42')                       // passes

So, you need to inspect the DOM, it looks like it's not what you expect.

Solution 3:[3]

The first attempt you were passing a jquery element to the .should() and although some chainers change the subject yours did not so it saved the jquery element as solNumber.

The second attempt invokes the .text() which was passed to the .then() it logs the number correctly. However, you did not return anything at the end of the .then() block, therefore, solNumber should hold the entire paragraph.

This should help you out to extract the specific number and save it as an alias.

cy.get('p')
  .invoke('text')
  .invoke('trim')
  .then(paragraph => {
        const matcher = /some/
        expect(paragraph).to.match(matcher) // check number is there

        const indexOfText = paragraph.match(matcher) // get index of match text
        return paragraph.substring(indexOfText.index, indexOfText.index + indexOfText[0].length) // return substring
   })
  .as('savedText')

cy.get('@savedText')
  .then(cy.log) // will print out the number you seek

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 Jumaane
Solution 2 Fody
Solution 3 jjhelguero