Cypress - preserve cookies between tests
This is in the Cypress docs, still it's something that can be said more than once.
When writing multiple tests, Cypress automatically clears all cookies by default to ensure a clean test state.
Although this is a good default behavior, it can be something you scratch your head on for a second or two, so - here's a quick example of what doesn't work and how to fix it:
context('Foo', () => {
describe('something', () => {
it('sets a cookie', () => {
cy.setCookie('cookieA', 'a');
})
it('gets a cookie', () => {
cy.getCookie('cookieA').should('have.property', 'value', 'a') // <- won't work
})
})
context('Foo', () => {
describe('something', () => {
it('sets a cookie', () => {
cy.setCookie('cookieA', 'a');
})
it('gets a cookie', () => {
cy.getCookie('cookieA').should('have.property', 'value', 'a') // <- won't work
})
})
cookieA is set in the first test but cleared in the context of the second test, unless you specifically tell Cypress to back off:
context('Foo', () => {
beforeEach(function () {
Cypress.Cookies.preserveOnce('cookieA');
})
...
context('Foo', () => {
beforeEach(function () {
Cypress.Cookies.preserveOnce('cookieA');
})
...
There's also an option that lets you preserve cookies by whitelisting them.