3

I am new to automation and coding in general and I would like to compare two session ID values with the following steps:

  1. Get first value right after logging in
  2. Refresh page
  3. Get second value and make an assertion.

I made a custom command in order to simplify things:

Cypress.Commands.add('getSessionId', () => {

    let sessionId
    cy.getCookie('development')
    .its('value').then(($value) => {
        sessionId = String($value)
    })    
})

I want the test script to look something like this:

let firstSessionId = cy.getSessionId()

cy.reload()

let secondSessionId = cy.getSessionId()

expect(firstSessionId).to.eq(secondSessionId)

There are two problems with this:

  1. I cannot access the values as strings in this scenario
  2. The expect runs before getting the ID's (i guess because of the asyncronous nature of cypress?)

I would appreciate any hint what I do wrong. Thanks

Vagdevi
  • 119
  • 9

2 Answers2

0

You can return the value from the custom command like this:

Cypress.Commands.add('getSessionId', () => {
  cy.getCookie('development')
    .its('value')
    .then((val) => {
      return cy.wrap(val)
    })
})

Then in your test, you can do this:

//Get First session Id
cy.getSessionId.then((sessionId1) => {
  cy.wrap(sessionId1).as('sessionId1')
})

//Refresh Page
cy.reload()

//Get Second session Id
cy.getSessionId.then((sessionId2) => {
  cy.wrap(sessionId2).as('sessionId2')
})

//Assert both
cy.get('@sessionId1').then((sessionId1) => {
  cy.get('@sessionId2').then((sessionId2) => {
    expect(sessionId1).to.eq(sessionId2)
  })
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
0

This is the simplest way to perform the test, no need for a custom command in this case.

cy.getCookie('development').its('value')
  .then(sessionId1 => {

    cy.reload()

    cy.getCookie('development').its('value')
      .then(sessionId2 => {
        expect(sessionId1).to.eq(sessionId2)
      })
  })

If you want a custom command for other reasons,

Cypress.Commands.add('getSessionId', () => {
  cy.getCookie('development').its('value')    // last command is returned
})

cy.getSessionId().then(sessionId1 => {

  cy.reload()

  cy.getSessionId().then(sessionId2 => {
    expect(sessionId1).to.eq(sessionId2)
  })
})
TesterDick
  • 3,830
  • 5
  • 18