问题描述
我想采取的步骤是:
- 启动 Cypress 测试套件并使用
cy.setCookie
设置 JSESSIONID cookie(已获取且是最新的) -
设置 cookie 后,然后使用
cy.visit
访问正在运行的应用
问题:
到目前为止我做了什么:
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>')
值得一提的是
任何帮助将不胜感激。提前致谢
解决方法
看看Provide an onBeforeLoad callback function
提到的示例配方(代码为 here)正在本地存储中设置令牌,但也应适用于 cookie
cy.visit('http://localhost:3000/#dashboard',{
onBeforeLoad: (contentWindow) => {
cy.setCookie('JSESSIONID',Cypress.env('JSESSIONID'),{
path: '/',...
})
}
})
我认为问题在于 cy.visit()
是清除一切的地方之一,但提供了钩子来解决这个问题。不过,我希望 preserve
也能正常工作。
我通过在使用 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>')
}