Local storage not clearing during Cypress test

Viewed 85

As part of my Cypress test, I am trying to log into an application.

The problem is that when I run the test a second time, I am already logged in, due to the previous test, so I'm not brought to the sign-in page & the login test fails.

Below is the storage when I run the test:

storageTab

I assume this bluelibs-token value is the reason I'm already logged in.

I have tried to clear the storage/cookies before the test run, but I'm still logged in.

Below is my test code:

before(() => {
    cy.clearLocalStorage('bluelibs-token')
    cy.clearLocalStorage()
    cy.clearCookies()
})

beforeEach(() => {
    cy.visit('/')
})

it('First Test Case', () => {
    cy.contains('Sign In').click();
    // this fails as I am brought to the user's account rather than the sign-in page (I would be brought to the sign-in page if I wasn't logged in)
})

Can someone please point out why this token is not being cleared, & how I can log in during each test?

2 Answers

You do not need to make these things in before function.

If you need to sign in, then your code may be (some pseudo-pseudocode :D ):

before(() => {
// visit sign in page
// fill form and submit
// the cookies & tokens are stored automatically
})

beforeEach(() => {
    cy.visit('/')
})

it('First Test Case', () => {
// here, because we have "beforeEach" set to '/' => we are on home page already (no need to sign in)
// do wat you want, eg:
    // got to another page
    // select an element etc.
})

// after that, we can write another test, and another, without signing in again

There is some Session Storage that you're not clearing.

The simplest way would be

before(() => {
    cy.clearLocalStorage('bluelibs-token')
    cy.clearLocalStorage()
    cy.clearCookies()
})

beforeEach(() => {
    cy.visit('/', {onBeforeLoad: (win) => { win.sessionStorage.clear()})
})

There's an open issue discussing here Clear sessionStorage in between tests #413

Currently we clear cookies and localStorage but somehow we missed automatically clearing sessionStorage as well.

This needs to be added, and we likely need to add a new cy.clearSessionStorage API command.

Toward the bottom of this log the experimental cy.session() command is mentioned and implies that later versions of Cypress (>= v8.2.0) will now clear session data.

But since it's experimental, it may be the clearing sequence needs some adjustment - i.e maybe it clears Session Storage between tests but not after runs.

Related