Javascript CYPRESS将cy.request响应存储在变量中
我有一个调用登录函数的文件 testing.jsJavascript CYPRESS将cy.request响应存储在变量中,javascript,cypress,Javascript,Cypress,我有一个调用登录函数的文件 testing.js var res = accounts.createSession(config.email_prod,config.password_prod,user_id) 在另一个文件中,我有: accounts.js export function createSession(email,password,user_id){ cy.request({ method:'POST', url:config.accou
var res = accounts.createSession(config.email_prod,config.password_prod,user_id)
在另一个文件中,我有:
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)
})
}
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
值,并将其返回到testing.js文件中的res
变量
但每次我存储令牌(在本例中,我将其存储在X中)并尝试打印它时,它总是说undefined
但我可以做cy.log(token),在login()函数上也可以,但这就是它所能做的,它不能存储到变量中
是否有另一种存储
令牌的方法?如果使用类似回调的参数,那么第二个函数将等待异步任务结束
export function createSession(email,password,user_id,callback){
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)
callback(response.body.access_token, user_id);
})
}
var login = function (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
}
// then call first fn
createSession(email,password,user_id,login);
我几乎有同样的问题。评论帮助了我
// 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
})
}