How do I make a Cypress Alias work between test cases?

Viewed 1033

I am getting inconsistent behaviour when using aliases in Cypress. I think it may be down to something with asynchronous behaviour between test cases.

From the Cypress documentation I tried both methods of referencing the Alias.

With 'this'

    it(`When clicks on an entry from the list`, () => {
        cy.get(`tr`)
            .eq(2)
            .within(() => {
                cy.get(':nth-child(1)')
                    .invoke('text')
                    .as(`etaId`)
                    .then(() =>
                        cy.get(':nth-child(1)')
                            .click()
                            .then(() => cy.wait(100))

                    )
            })
    })

    it(`Then ETA details are shown`, () => {

        cy.contains(`ETA: ${this.etaId}`)
            .should(`be.visible`)
    })

Gives the error

Cannot read property 'etaId' of undefined

With 'cy.get(@{alias}).then()'

    it(`When clicks on an entry from the list`, () => {
        cy.get(`tr`)
            .eq(2)
            .within(() => {
                cy.get(':nth-child(1)')
                    .as(`etaIdCell`)
                    .invoke('text')
                    .as(`etaId`)
                    .then(() =>
                        cy.get(':nth-child(1)')
                            .click()
                            .then(() => cy.wait(100))

                    )
            })
    })

    
    it(`Then ETA details are shown`, () => {
        cy.get(`@etaId`)
            .then(id => {
                cy.contains(`ETA: ${id}`)
                    .should(`be.visible`)
            })
    })

I know that the selector for the alias is correct because the following code when I do everything in the same test case works correctly


      it(`When clicks on an entry from the list`, () => {
        cy.get(`tr`)
            .eq(2)
            .within(() => {
                cy.get(':nth-child(1)')
                    .invoke('text')
                    .as(`etaId`)
                    .then(() =>
                        cy.get(':nth-child(1)')
                            .click()
                            .then(() => cy.wait(100)
                    )
            )
        })
        .then(() => {
            cy.get(`@etaId`)
                .then(id => {
                    cy.contains(`ETA: ${id}`)
                        .should(`be.visible`)
                })
        })
    })

and I can see in the dev tools

enter image description here

I would appreciate any help.

Thanks

1 Answers

You're right. Your alias syntax is correct; but in the one case your alias is encapsulated in one of the it blocks and when the test is complete, it loses the context of the etaId. You'd have to set the alias in a beforeEach block or in a shared scope so that your test can see it.

Related