JS + Cypress:无法从函数中获取输出
JS + Cypress : unable to get the output from a function
我最近开始玩 JS 并研究 Cypress 来编写一些简单的测试自动化。
我的代码如下:
Cypress.Commands.add("setup", (email, password) => {
getAccessToken(email, password).then(console.log)
})
function getAccessToken (email, password) {
cy.request('POST', 'testurl',{
"email": email,
"password": password
}).then((response) => {
return response.body.access_token
})
}
console.log 打印 access_token 就好了,如果我把它放在 getAccessToken 中 return 语句所在的位置..但是如果我调用它,console.log 打印不明即使在使用 .then 后命令设置,(我的目标是获取 access_token 并将其用作“设置”中另一个函数的输入)
您的 return
仅 return 是 Cypress 链中的 response.body.access_token
。如果您在函数中的 .then()
之后添加一个 .then()
,您将正确地产生该值。
相反,您可以 return 函数中的整个 cy.request()
链,并查看响应。
function getAccessToken (email, password) {
return cy.request('POST', 'testurl',{
"email": email,
"password": password
}).then((response) => {
return response.body.access_token
})
}
使用此代码测试:
const getTest = () => {
return cy.request('http://www.google.com').then((res) => {
return res.body;
});
};
getTest().then(console.log);
我最近开始玩 JS 并研究 Cypress 来编写一些简单的测试自动化。
我的代码如下:
Cypress.Commands.add("setup", (email, password) => {
getAccessToken(email, password).then(console.log)
})
function getAccessToken (email, password) {
cy.request('POST', 'testurl',{
"email": email,
"password": password
}).then((response) => {
return response.body.access_token
})
}
console.log 打印 access_token 就好了,如果我把它放在 getAccessToken 中 return 语句所在的位置..但是如果我调用它,console.log 打印不明即使在使用 .then 后命令设置,(我的目标是获取 access_token 并将其用作“设置”中另一个函数的输入)
您的 return
仅 return 是 Cypress 链中的 response.body.access_token
。如果您在函数中的 .then()
之后添加一个 .then()
,您将正确地产生该值。
相反,您可以 return 函数中的整个 cy.request()
链,并查看响应。
function getAccessToken (email, password) {
return cy.request('POST', 'testurl',{
"email": email,
"password": password
}).then((response) => {
return response.body.access_token
})
}
使用此代码测试:
const getTest = () => {
return cy.request('http://www.google.com').then((res) => {
return res.body;
});
};
getTest().then(console.log);