I have a feeling there is already an answer to this, but could not find one that is generally applicable.
Maybe a good approach is to use cypress-data-session. There is a lot of documentation but here is a sample usage:
beforeEach(() => {
// let's say you want to set up the value "A"
cy.dataSession(
'A', // data name
() => 'a', // data creation commands
(x) => x === 'a', // data validation function
)
})
it('has object A', () => {
expect(Cypress.getDataSession('A')).to.equal('a')
})
Another option I have seen is using the Cypress environment as a data store.
// setting
Cypress.env('my-value', variable)
// retrieving
const myValue = Cypress.env('my-value')
The downside IMO is - it's not elegant to use Cypress.env()
everywhere, and it can lose the values if Cypress browser resets.