javascript - CYPRESS 将 cy.request 响应存储在变量中
问题描述
我有一个调用登录功能的文件
测试.js
var res = accounts.createSession(config.email_prod,config.password_prod,user_id)
在另一个文件上,我有这个:
帐户.js
export function createSession(email,password,user_id){
cy.request({
method:'POST',
url:config.accounts_prod + '/token',
headers:{
'authorization': 'Basic testestestestest'
},
qs:{
'grant_type':'password',
'username':email,
'password':password
}
}).then((response)=>{
var X = response.body.access_token
cy.log("create session " + x)
login(response.body.access_token, user_id)
})
}
export function login(token,user_id){
var result = cy.request({
method:'POST',
url:config.ws_prod + '/login.pl',
headers:{
'authorization': token,
'Content-Type' : 'application/x-www-form-urlencoded'
},
body:'user_id='+user_id+'&device_id='+device_id+'&os_type='+os_type
})
return token
}
所以我想存储token
值并将其返回到res
testing.js 文件上的变量,但是每次我存储令牌(在这个例子中我将它存储在 X 中)并且我尝试打印它时,它总是说undefined
但我可以做 cy.log(token ) 并且在 login() 函数上很好,但这就是它所能做的,它不能存储到变量中我还有另一种存储方式token
吗?
解决方案
我有几乎同样的问题。评论这个答案对我有帮助
// testing.js
let res = null;
before(() => {
accounts.createSession(config.email_prod, config.password_prod, user_id).then((responseToken) => {
res = responseToken;
console.log('response token', responseToken);
});
});
it('My tests ...', () => {
console.log('...where I can use my session token', res);
});
// accounts.js
export function createSession(email, password, user_id) {
cy.request({
method: 'POST',
url: config.accounts_prod + '/token',
headers: {
'authorization': 'Basic testestestestest'
},
qs: {
'grant_type': 'password',
'username': email,
'password': password
}
}).then((response) => {
var x = response.body.access_token
cy.log("create session " + x)
login(response.body.access_token, user_id)
return response.body.access_token; // needs return statement
})
}
推荐阅读
- scala - 如何在使用 reducebykey 时限制单个记录中的对数
- django - 如何在 django 的核心模型中添加“unique_together”约束?
- c# - n个sql交集
- c# - C# 有没有办法将 DllImport 与泛型方法类型一起使用?
- sql - 如何选择具有唯一列值的 N 最近行
- r - Shiny中的动态文本框列表
- mysql - 无法使用 MySQL Workbench 运行脚本
- r - 在 mutate_all 的函数内部使用 one_of/vars
- google-cloud-platform - 我可以使用 API 获取堆栈驱动程序策略事件吗?
- javascript - JS下拉插入符号动画中断输入