首页 > 解决方案 > 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值并将其返回到restesting.js 文件上的变量,但是每次我存储令牌(在这个例子中我将它存储在 X 中)并且我尝试打印它时,它总是说undefined 但我可以做 cy.log(token ) 并且在 login() 函数上很好,但这就是它所能做的,它不能存储到变量中我还有另一种存储方式token吗?

标签: javascriptcypress

解决方案


我有几乎同样的问题。评论这个答案对我有帮助

// 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
    })
}

推荐阅读