Assigning text value to variable in cypress to compare changes

Viewed 3853

I'm trying to compare if the value changed correctly after doing certain things in the app. First I'm trying to assign the value using cypress aliases, but it does not find the value at all. I tried using let and const and same problem exists.

So here is the code which gives error:

 cy.get('[data-cy=AmountAll]', { timeout: 15000 }).invoke('text').then((text) => {
        text.replace(/\D/g,'').as("myAlias")
      })

I want to reuse this txt variable so that I can compare it later:

  cy.get('[data-cy=AmountAll]', { timeout: 15000 }).invoke('text').then((text) => {
            expect(@myAlias).to.be.gte(text.replace(/\D/g,''));
          })

So its basically checking if the value changed after doing some set of procedures and is smaller than before. But I cant find correct way to hold this value in a variable

3 Answers

The text that you are getting is in string, you have to convert in into a Number (using parseInt) if you want to compare the two. And you can use this to access myAlias (As, under the hood, aliasing basic objects and primitives utilizes Mocha’s shared context object: that is, aliases are available as this.*)

cy.get('[data-cy=AmountAll]', {
    timeout: 15000
}).invoke('text').then((text) => {
    const amountAllBefore = parseInt(text.replace(/\D/g, '')) //this will only work if text.replace(/\D/g, '') returns a number but is string
    cy.wrap(amountAllBefore).as('myAlias')
})

cy.get('[data-cy=AmountAll]', {
    timeout: 15000
}).invoke('text').then((text) => {
    const amountAllAfter = = parseInt(text.replace(/\D/g, '')) //this will only work if text.replace(/\D/g, '') returns a number but is string
    expect(this.myAlias).to.be.greaterThan(amountAllAfter)
})

That might be because you think that Cypress code runs synchronously. But that's not the case. I recommend starting with this senction of the documentation and read all other sections this one links, e.g. this one.

In the second section I linked, there's some code that basically answers your question, even though it deals with a different context.

So, you might want to do something like this:

cy.get('[data-cy=AmountAll]', { timeout: 15000 }).invoke('text').then((text1) => {
    const text1 = text1.replace(/\D/g,'');

    // some actions you need to perform

    cy.get('[data-cy=AmountAll]', { timeout: 15000 }).invoke('text').then((text2) => {
        const text2 = text2.replace(/\D/g,'');

        expect(text1).to.eq(text2);
    });
});

You cannot retrieve an alias inside and expect() like that.

Try closure (similar to @pavelsaman's suggestion), but with cy.get('@myAlias') since you want the two blocks separated.

cy.get('@myAlias').then(text1 => {
  cy.get('[data-cy=AmountAll]', { timeout: 15000 }).invoke('text').then((text2) => {
    expect(text1).to.be.gte(text2.replace(/\D/g,''));
  })      
})
Related