在 Cypress 中跨测试保留 cookie/localStorage 会话 [英] Preserve cookies / localStorage session across tests in Cypress

查看:34
本文介绍了在 Cypress 中跨测试保留 cookie/localStorage 会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存/保留/保留由 cy.request() 设置的 cookie 或 localStorage 令牌,这样我就不必使用自定义命令来登录每个测试.这应该适用于存储在客户端的 localStorage 中的诸如 jwt(json 网络令牌)之类的令牌.

I want to save/persist/preserve a cookie or localStorage token that is set by a cy.request(), so that I don't have to use a custom command to login on every test. This should work for tokens like jwt (json web tokens) that are stored in the client's localStorage.

推荐答案

来自 Cypress 文档

From the Cypress docs

对于持久性 cookie:默认情况下,赛普拉斯会在每次测试前自动清除所有 cookie,以防止建立状态.

For persisting cookies: By default, Cypress automatically clears all cookies before each test to prevent state from building up.

您可以使用 Cypress.Cookies api 配置要在测试中保留的特定 cookie:

You can configure specific cookies to be preserved across tests using the Cypress.Cookies api:

// now any cookie with the name 'session_id' will
// not be cleared before each test runs
Cypress.Cookies.defaults({
  preserve: "session_id"
})

注意:在 Cypress v5.0 之前,配置键是白名单",而不是保留".

NOTE: Before Cypress v5.0 the configuration key is "whitelist", not "preserve".

用于持久化localStorage:它不是内置于ATM中的,但您现在可以手动实现它,因为清除本地存储的方法公开为Cypress.LocalStorage.clear.

For persisting localStorage: It's not built in ATM, but you can achieve it manually right now because the method thats clear local storage is publicly exposed as Cypress.LocalStorage.clear.

您可以备份此方法并根据发送的密钥覆盖它.

You can backup this method and override it based on the keys sent in.

const clear = Cypress.LocalStorage.clear

Cypress.LocalStorage.clear = function (keys, ls, rs) {
  // do something with the keys here
  if (keys) {
    return clear.apply(this, arguments)
  }

}

这篇关于在 Cypress 中跨测试保留 cookie/localStorage 会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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