定义命令
Cypress.Commands.add('getLocalStorage', () => {
const state = window.localStorage.getItem('state');
return JSON.parse(state);
});
使用命令
const localState = cy.getLocalStorage();
结果
localState变量包含以下值:
chainerId: "chainer6"
firstCall: false
specWindow: Window {parent: global, opener: null, top: global, length: 0, frames: Window, …}
useInitialStack: false
userInvocationStack: " ......"
使用5.5.0版本
只需使用javascript函数
const getLocalStorage = () => {
const state = window.localStorage.getItem('state');
return JSON.parse(state);
});
const localState = getLocalStorage();
自定义命令生成用于链接的链接器
cy.getLocalStorage().then(state => ...
Cypress在测试中从javascript异步运行命令队列。如果您希望一段JS在队列中同步运行,那么您可以创建一个自定义命令。
或者,您可以使用.then()
挂接到命令序列中。
您使用了错误的window
。全局窗口是为Cypress runner设置的,cy.state('window')
会为您获取iframe中的窗口,即应用程序正在使用的窗口。
Cypress.Commands.add('getLocalStorage', () => {
const state = cy.state('window').localStorage.getItem('state');
return JSON.parse(state);
});
Cypress文档建议不要分配Cypress命令的返回值(例如const localState = cy.getLocalStorage();
(
https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-值