跨测试保存本地存储,以避免重新认证

编程入门 行业动态 更新时间:2024-10-22 02:48:18
本文介绍了跨测试保存本地存储,以避免重新认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是否可以在各个测试之间保存localStorage的状态。 主要是因为我想避免每次测试都重新认证。我意识到我可以创建一个将API请求发送到后端的命令,以避免通过身份验证流程,但是由于种种原因,这在我的情况下不起作用。

I'm wondering if it is possible to save the state of localStorage across tests. Mainly because I want to avoid re-authentication on each test. I realize that I can create a command that sends an API request to our backend to avoid going through the auth flow but for various reasons this won't work in my situation.

我在问是否可以有这样的工作流程:

I am asking if it possible to have a workflow like this:

  • 进入登录页面:身份验证返回响应并将会话保存到本地存储中
  • 以某种方式坚持本地存储...
  • 以身份验证方式通过其他测试用户
  • 推荐答案

    这就是我最终要做的事情:

    Here's what I ended up doing:

  • 转到登录页面:验证至此,我们有了要在两次测试之间保留的数据,但我们不允许将localStorage列入白名单。 但是,我们允许将白名单cookie
  • Go to login page: Authenticate At this point we have data we want to persist between tests in localStorage but we are not allowed to whitelist localStorage. However, we are allow to whitelist cookies
  • 我的 support / commands.js 充当助手

    const sessionKeys = { authTokens: 'auth.tokens', sessionConfig: 'session.config', }; // The concatenation of username and cid will be the key to set the session Cypress.Commands.add('persistSession', (key) => { const authTokens = localStorage.getItem(key); cy.setCookie(key, authTokens); }); Cypress.Commands.add('restoreSession', (key) => { cy.getCookie(key).then(authTokens => { localStorage.setItem(key, authTokens.value); }); });

  • 所以我们称 cy.persistSession(key)登录后,这意味着我们已将所有身份验证保存为cookie,并将其存储在 support / index.js 内的白名单中
  • So we call cy.persistSession(key) after we login, which means we have all the authentication saved as cookies which are whitelisted inside of support/index.js with code.
  • 像这样:

    Cypress.Cookies.defaults({ whitelist: function(cookie){ // Persist auth stuff const reAuthTokens = new RegExp('.*auth\.tokens'); if(reAuthTokens.test(cookie.name)){ return true; } return false; } });

  • 现在,我们随时都需要在我们的内部使用身份验证令牌在运行其他测试之前,我们 cy.restoreSession(key),我们应该很好!
  • Now anytime we need our auth tokens inside our other tests before running them we cy.restoreSession(key) and we should be good!
  • 更多推荐

    跨测试保存本地存储,以避免重新认证

    本文发布于:2023-11-10 22:10:25,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1576595.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:测试   以避免

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!