首页 文章

CYPRESS在变量中存储cy.request响应

提问于
浏览
0

我有一个调用登录功能的文件

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(令牌)它在login()函数上很好,但这就是它可以做的全部,它不能存储到变量中是否有另一种方式来存储 token

1 回答

  • 0

    也许如果我使用类似参数的回调,那么第二个函数将等待异步任务结束

    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
    }
    

    //然后先调用fn

    createSession(email,password,user_id,login);
    

    对不起我的英语不好

    来自墨西哥的你好

相关问题