Skip to content
Advertisement

Cypress Best Practice – 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:

  • Get the number or results displayed (‘counts’), store it in a .then() function
  • Change the use
  • Get the number of results displayed (‘new_counts’), store it in a new .then function
  • Compare counts and new_counts in the 2nd .then() function
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.

Advertisement

Answer

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)
      })
    })
  })
})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement