我有一个调用登录功能的文件
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.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()函数上还可以,但这就是它所能做的,不能将其存储到变量中
我还有另一种存储token
的方法吗?
答案 0 :(得分:1)
也许如果我使用类似参数的回调,那么第二个函数将等待异步任务结束
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);
答案 1 :(得分:0)
我遇到了几乎相同的问题。对this answer的评论对我有帮助
// 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
})
}