I was using this code in my Cypress tests using Cypress version 8:
beforeEach(() => {
Cypress.Cookies.preserveOnce(
'csrftoken',
'sessionid',
// ...other cookies...
)
})
and now I have finally upgraded to Cypress 13 and am told to use cy.session
instead. I'm having trouble figuring out what the equivalent of the above would look like based on the examples provided in the documentation and migration guide.
The use of preserveOnce
in beforeEach
was working perfectly for ensuring cookies persisted like they would in a browser session between all of my tests. Could someone please explain how I can code the equivalent of the above code using Cypress 13+?
If I wrap the requests that create the cookies in session
calls, the page is automatically cleared afterwards so the next tests fail. It seems I'll need to majorly refactor my test suite, or am I missing a simpler method of achieving the same effect as preserveOnce
?
Here is an example of one of my specs:
context('the cookie preferences panel', () => {
before(() => {
cy.visit('/')
})
it('is displayed correctly by default', () => {
cy.get('#cookie-preferences')
.should('be.visible')
.and('contain', 'We value your privacy')
})
it('remains visible when page is refreshed', () => {
cy.reload()
cy.get('#cookie-preferences').should('be.visible')
})
context('when the accept button is clicked', () => {
before(() => cy.get('#cookie-preferences .accept').click())
it('the banner is no longer visible', () => {
cy.get('#cookie-preferences').should('not.be.visible')
})
it('does not open when page is refreshed', () => {
cy.reload()
cy.get('#cookie-preferences').should('not.be.visible')
})
})
})
I tried using cy.session('cookies', () => {cy.visit('/')})
in before
for preserving the cookies generated in that request in the subsequent it
tests, but they failed due to the new testIsolation
setting that I was unaware of, see accepted answer below
Probably you are getting a about:blank (clear page) because of a new Cypress setting called test isolation. You can know more about test isolation here
When test isolation is enabled, Cypress resets the browser context before each test by:
Because the test starts in a fresh browser context, you must re-visit your application and perform the series of interactions needed to build the dom and browser state for each test.
You should try to refactor your tests to rely on test isolation, but if this is something you don't want to do at the moment you can simply turn off this test isolation setting.