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

Save local storage across tests to avoid re-authentication

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

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

  1. 转到登录页面:验证取回响应并将会话保存到本地存储
  2. 以某种方式保留本地存储...
  3. 以经过身份验证的用户身份进行其他测试

任何你能在 JS 中做的事情,你都可以在 cypress 测试中做。如果您有某种方法可以在本地存储中存储信用(身份验证令牌等),我认为您没有理由不能这样做。如果赛普拉斯在测试之间清除您的本地存储,您将必须编写一个 beforeEach 挂钩,在每次测试之前将经过身份验证的令牌(由您硬编码)保存到本地存储。

这是我最后做的事情:

  1. 转到登录页面:验证 此时我们有数据想要在 localStorage 中的测试之间保留,但我们不允许将 localStorage 列入白名单。 但是,我们可以 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,这些 cookie 在 support/index.js 中使用代码列入白名单。

像这样:

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) 之前,任何时候我们都需要在我们的其他测试中使用我们的身份验证令牌,我们应该很好!

下面是有用的 link 可以像您一样解决我的问题:Preserve cookies through multiple tests

我的代码如下:

    const login = () => { 
      cy.visit('http://0.0.0.0:8080/#/login');    
      cy.get('#username').type('username'); 
      cy.get('#password').type('1234password$'); 
      cy.get('#login-button').click();
    }

    describe('UI', () => {
      // beforeEach(login);
      beforeEach(() => {
        login(); 
        Cypress.Cookies.preserveOnce('session_id', 'remember_token'); 
      });
    });

希望能帮到你。

您可以使用 cypress-localstorage-commands 包在测试之间保留 localStorage,这样您就可以只登录一次:

在support/commands.js:

import "cypress-localstorage-commands";

在你的测试中:

before(() => {
  // Do your login stuff here
  cy.saveLocalStorage();
});

beforeEach(() => {
  cy.restoreLocalStorage();
});