如何在访问本地主机上运行的 React 应用程序之前在 Cypress 中设置 cookie

问题描述 投票:0回答:4

我想采取的步骤是:

  1. 启动 Cypress 测试套件并使用
    cy.setCookie
    设置 JSESSIONID cookie(已获取且是最新的)
  2. 设置cookie后,然后使用
    cy.visit
    访问正在运行的应用程序

问题:

  • cy.visit
    运行之前未设置cookie,这会导致应用程序重定向到未经授权的页面

到目前为止我所做的:

Cypress.Cookies.defaults({
  preserve: 'JSESSIONID'
})

cy.setCookie('JSESSIONID', Cypress.env('JSESSIONID'), {
  path: '/',
  domain: '<domain.name>',
  httpOnly: true,
  secure: true,
  sameSite: 'no_restriction',
  log: true,
}).then(() => cy.visit('localhost:3000/<authenticated-route>')

可能值得一提的是 的形式为 www.staging.etc.com 而在本地运行: localhost:3000/

任何帮助将不胜感激。预先感谢

testing cookies cypress jsessionid
4个回答
1
投票

我通过在使用 cy.visit 之前执行 cy.request 登录解决了该问题。

代码看起来像这样:

const login = () => {
  const headers = new Headers()
  headers.append("Content", "application/x-www-form-urlencoded")
  headers.append("Accept-Encoding", "gzip:deflate")
  headers.append("Content-Type", "application/x-www-form-urlencoded")

  cy.request({
    url: Cypress.env("LOGIN_URL"),
    method: 'POST',
    form: true,
    headers,
    body: {
      "email": Cypress.env("EMAIL"),
      "password": Cypress.env("PASSWORD")
    }
  }).then((response) => {
    console.log(response)
    console.log(response.body)
    setCookie(response.COOKIE)
  })
}

export const loginAndStartTests = () => {
  login()
  cy.visit('/<homepage>')
}

0
投票

看一下提供onBeforeLoad回调函数

提到的示例配方(代码是here)正在本地存储中设置令牌,但也应该适用于cookie

cy.visit('http://localhost:3000/#dashboard', {
  onBeforeLoad: (contentWindow) => {
    cy.setCookie('JSESSIONID', Cypress.env('JSESSIONID'), {
      path: '/',
      ...
    })
  }
})

我认为问题在于

cy.visit()
是所有东西都被清除的地方之一,但提供了钩子来解决这个问题。不过,我希望
preserve
也能发挥作用。


0
投票

您需要从参数设置 cookie

contentWindow
:

cookie 设置器实用程序:

export const setCookieToContentWindow = (
  contentWindow,
  name,
  value,
  { expireMinutes = 1 } = {},
) => {
  const date = new Date();
  const expireTime = expireMinutes * 60 * 1000;

  date.setTime(date.getTime() + expireTime);

  const assignment = `${name}=${encodeURIComponent(value)}`;
  const expires = `expires=${date.toGMTString()}`;
  const path = 'path=/';

  contentWindow.document.cookie = [assignment, expires, path].join(';');
};

使用

onBeforeLoad

cy.visit('http://localhost:3000/#dashboard', {
  onBeforeLoad: (contentWindow) => {
    setCookieToContentWindow(contentWindow, 'COOKIE_NAME', 'COOKIE_VALUE');
  },
});

0
投票

您还可以做的是使用

Cookie
HTTP header:

设置 cookie
cy.visit('/whatever', {
  headers: {
    'Cookie': '<cookie-name>=<cookie-value>'
}})
© www.soinside.com 2019 - 2024. All rights reserved.