javascript - 自定义命令中的赛普拉斯常量/变量
问题描述
我有以下用于 cypress 自定义命令的代码,用于生成用户会话 cookie:
Cypress.Commands.add('getSession', (email, password) => {
return cy.request({
url: 'xxx',
method: 'POST',
body: {
email,
password,
}
})
.then((response) => {
let body = (response.body);
expect(response.status).to.eq(200);
cy.log('Id - ' + body.customerId);
let session = "SESSIONID=" + body.Cookies.SESSIONID + ";" ...
cy.log('raw session data - ' + session)
//Base64 encode
cy.writeFile('tmp/rawStr.txt', session, 'utf8');
cy.readFile('tmp/rawStr.txt', 'base64').then((cookie) => {
cy.log('base64 string - ' + cookie);
});
})
});
我想在另一个自定义命令中重新使用“cookie”中的值,但是每当我运行测试时,它都会说 cookie 未定义。我在该测试中所做的只是创建一个 Cookie 标头,其中包含我在上述步骤中创建的 base64 字符串。
有问题的自定义命令如下所示:
Cypress.Commands.add('createThing', (name) => {
return cy.request({
url: 'xxx',
method: 'POST',
headers: {
'Cookie' : 'client_token=' + cookie,
'Content-Type' : 'application/json'
},
body: {
'name' : name
}
})
.then((response) => {
let body = (response.body);
expect(response.status).to.eq(200);
cy.log(body);
});
});
如何获取自定义命令来共享该 cookie 值?
我的规范文件调用自定义命令,如下所示:
/// <reference types="Cypress" />
describe('deletes a user thing', function() {
it('create a thing via the api', function() {
cy.getSession('xxxx', 'xxxxx')
cy.createThing('thing')
})
})
解决方案
我建议拆分为 2 个自定义命令。第一个将获得一个coockie,并返回它,另一个方法将重用第一个的结果。就像是:
// Method to get coockie
Cypress.Commands.add('getCookie', (email, password) => {
cy.request({
url: 'xxx',
method: 'POST',
body: {
email,
password,
}
}).then((response) => {
expect(response.status).to.eq(200);
let cookie = response.body.Cookies
return cookie
})
})
// Method to get sessionId that will reuse getCoockie method
Cypress.Commands.add('getSession', (email, password) => {
cy.getCookie(email, password).then(cookie => {
let session = "SESSIONID=" + cookie.SESSIONID + ";"
return session
})
})
// test
describe('test', () => {
it('bla bla', () => {
const email = 'test@test.com'
const pass = 'pass'
cy.getSession(email, pass).then(session => {
console.log(session)
})
})
})
推荐阅读
- django - 在 wagtail 中,我如何设置 v2 api 以将完整的基本 URL(例如 http://localhost:8000" )附加到蒸汽场图像和富文本嵌入?
- powershell - 识别当前活动窗口,向另一个窗口发送击键并返回到当前活动窗口
- android - 无法在 Android Studio 中构建项目
- javascript - e.preventDefault() 不允许我提交表单
- r - 如何使用 R 仅在散点图 3d 图中更改点颜色?
- intellij-idea - IntelliJ 中 ant 的导入问题
- java - java.lang.NoSuchMethodError: cucumber.runtime.Runtime
- react-native - 在注册时使用 withAuthenticator 放大获取用户属性
- typescript - 派生类中扩展构造函数参数的正确 TypeScript 类型
- python - Python 3 Turtle 模块 > .goto() 方法