Norbert Kiss
Norbert Kiss

Reputation: 141

How to set a sessionStorage in Cypress?

I need to change the value of one of the parameters in the sessionStorage but I'm not even sure if this is possible through Cypress. Couldn't find any useful information about this in their documentation.

This is the javascript code that I'm trying to run with Cypress without any success:

var data = JSON.parse(sessionStorage.getItem("vuex"))
data.country = "DE"
sessionStorage.setItem("vuex", JSON.stringify(data))

It works perfectly fine if I execute it in the console but I don't know how to make it work with Cypress.

Even if I write a simple javascript code like

console.log(sessionStorage.getItem("vuex"))

It returns Null with Cypress.

Does anyone have any idea why I am getting null for this javascript code and if this operation is even possible with Cypress?

Upvotes: 2

Views: 6940

Answers (2)

Pavel Lobarev
Pavel Lobarev

Reputation: 321

Here is a nice example of setting a user in session storage in Cypress

cy.fixture("user.json").then((users) => {
        // Get the user fixture
        let user = user.sessionStorageContent;

        // Stringify the user object
        let userContent = JSON.stringify(user);

        cy.window().then((win) => {
          // Set the user object in the sessionStorage
          win.sessionStorage.setItem("user", userContent);
        });
      });

Upvotes: 0

Norbert Kiss
Norbert Kiss

Reputation: 141

Found the solution:

cy.window().then( win => {

    var data = JSON.parse(sessionStorage.getItem("vuex"))
    data.country = "DE"
    sessionStorage.setItem("vuex", JSON.stringify(data))

})

Upvotes: 12

Related Questions