javascriptcypress

How to store and compare two values?


I want to store a value, then perform an action and assert that the value has not changed. I do have a code that works but I would like to have input if there is a more elegant solution.

The basic idea is:

describe('Store and compare a value', () => {
    it('store and compare', () => {

        cy.login()
        cy.visit('url2')
        cy.get('.total-count-results').invoke('text')
            .then((text) => {
                const counts = text 
                cy.get('.medium.col100 > .filterwrapper > input').type('Test Dummy',{force: true})
                cy.get('.medium.col100 > .filterwrapper > input').type('{enter}')
                cy.get('.total-count-results').invoke('text')
                    .then((text) => {
                        const new_counts = text
                        expect(new_counts).to.eq(counts)
                    })
            })
    })
})

That is the best I could come up with to handle asynchronicity.


Solution

  • You can use aliases for this and do something like this:

    describe('Store and compare a value', () => {
      it('store and compare', () => {
        cy.login()
        cy.visit('url2')
        cy.get('.total-count-results').invoke('text').as('counts')
        cy.get('.medium.col100 > .filterwrapper > input').type('Test Dummy', {
          force: true,
        })
        cy.get('.medium.col100 > .filterwrapper > input').type('{enter}')
        cy.get('.total-count-results').invoke('text').as('new_counts')
        cy.get('@counts').then((counts) => {
          cy.get('@new_counts').then((new_counts) => {
            expect(new_counts).to.eq(counts)
          })
        })
      })
    })