跨测试保存本地存储,以避免重新认证 [英] Save local storage across tests to avoid re-authentication

查看:51
本文介绍了跨测试保存本地存储,以避免重新认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在各个测试之间保存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:


  1. 进入登录页面:身份验证返回响应并将会话保存到本地存储中

  2. 以某种方式坚持本地存储...

  3. 以身份验证方式通过其他测试用户


推荐答案

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

Here's what I ended up doing:


  1. 转到登录页面:验证
    至此,我们有了要在两次测试之间保留的数据,但我们不允许将localStorage列入白名单。
    但是,我们允许将白名单cookie

  1. 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);
  });

});




  1. 所以我们称 cy.persistSession(key)登录后,这意味着我们已将所有身份验证保存为cookie,并将其存储在 support / index.js 内的白名单中

  1. 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;
  }
});




  1. 现在,我们随时都需要在我们的内部使用身份验证令牌在运行其他测试之前,我们 cy.restoreSession(key),我们应该很好!

  1. Now anytime we need our auth tokens inside our other tests before running them we cy.restoreSession(key) and we should be good!

这篇关于跨测试保存本地存储,以避免重新认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆