'JSESSIONID cookie not preserved using Cypress

We are currently logging into our application using the cy.request() method and here the JSESSIONID cookie is set. After that we do various other requests also using cy.request() but none of them work because the JSESSIONID cookie appears not to be set in the headers. Before, we dealt with this by using Cypress.Cookies.preserveOnce('JSESSIONID') in the index.js file of the support folder. I have played around using various options for the cookies such as moving the preserveOnce in the tests, using whitelist, etc but none of them have worked. I have also automated the login using the UI but immediately after the login we get session expired.

Is there any way to control this cookie? We don't understand why it stopped working all of a sudden (the endpoint was modified recently though). Currently we have Cypress version 4.7.0 and I have tried with version 7.0.0 as well.

Has anyone ever encountered such an issue?



Solution 1:[1]

Could you try to place it in the test file with the beforeEach hook?

ex:

beforeEach(() => {
        Cypress.Cookies.preserveOnce('<id>')
    })

Solution 2:[2]

Did you try to pass the cookie/s in the spec itself?

Inside your describe, please add this code to keep the cookie throughout the spec.

Cypress.Cookies.defaults({
    preserve: 'JSESSIONID'
})

If multiple cookies are needed, they can be in an array:

Cypress.Cookies.defaults({
    preserve: ['JSESSIONID', 'Cookie2']
})

Solution 3:[3]

Although the official documentation recommends using the 'Cypress.Cookies.preserveOnce' in the beforeEach (Preserve-Once), in my case it didn't work. I had to put it in the afterEach in my case it looked like this:

        afterEach(function(){
            Cypress.Cookies.preserveOnce('JSESSIONID')
        })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prabhu Mohan
Solution 2 Pradeep SJ
Solution 3