Reputation: 9899
DEFINE COMMAND
Cypress.Commands.add('getLocalStorage', () => {
const state = window.localStorage.getItem('state');
return JSON.parse(state);
});
USE COMMAND
const localState = cy.getLocalStorage();
RESULT
localState variable holds this value:
chainerId: "chainer6"
firstCall: false
specWindow: Window {parent: global, opener: null, top: global, length: 0, frames: Window, …}
useInitialStack: false
userInvocationStack: " ......"
Using version 5.5.0
Upvotes: 0
Views: 179
Reputation: 164
The Cypress documentation advises against assigning the return value of Cypress commands (eg. const localState = cy.getLocalStorage();
)
https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values
Upvotes: 0
Reputation:
Just use a javascript function
const getLocalStorage = () => {
const state = window.localStorage.getItem('state');
return JSON.parse(state);
});
const localState = getLocalStorage();
Custom commands produce chainers that are for, well, chaining
cy.getLocalStorage().then(state => ...
Cypress runs a command queue asynchronously from the javascript in the test. If you want a piece of JS to run synchronously inside the queue, you create a custom command.
Or you can use .then()
to hook into the command sequence.
You are using the wrong window
. The global window is for the Cypress runner, cy.state('window')
gets you the window in the iframe, the one the app is using.
Cypress.Commands.add('getLocalStorage', () => {
const state = cy.state('window').localStorage.getItem('state');
return JSON.parse(state);
});
Upvotes: 2