本文介绍了如何从赛普拉斯自定义命令返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在轮询任务以进行异步rest调用,如何从此赛普拉斯自定义函数返回taskStatus的值.我想在我的规格文件中使用此值.这是正确的方法吗?
I am polling task for async rest call, how do I return value of taskStatus from this Cypress custom function. I want to use this value in my spec file. Is this the right way?
**Cypress.Commands.add("pollTask", (TASK_URI,token) => {
// const regex = /Ok|Error|Warning/mg;
var taskStatus =''
cy.log(" *Task_URI : " + TASK_URI)
cy.log(" *X-Auth-token : " + token)
cy.server()
var NEWURL = Cypress.config().baseUrl + TASK_URI
cy.request({
method: 'GET',
url: NEWURL,
failOnStatusCode: false,
headers: {
'x-auth-token': token
}
}).as('fetchTaskDetails')
cy.log("local: " + token)
cy.get('@fetchTaskDetails').then(function (response) {
taskStatus = response.body.task.status
cy.log('task status: ' + taskStatus)
expect(taskStatus).to.match(regex)
})
return taskStatus
})**
推荐答案
您必须返回Promise.这是一个简单的获取/设置示例(来自赛普拉斯自定义命令文档).
You must return a Promise. Here's a simple get/set example from Cypress Custom Commands documentation.
在您的情况下,您可以像这样返回 taskStatus
:
In your case, you can return taskStatus
like this:
Cypress.Commands.add("pollTask", (TASK_URI,token) => {
const regex = /Ok|Error|Warning/mg;
// var taskStatus =''
cy.log(" *Task_URI : " + TASK_URI)
cy.log(" *X-Auth-token : " + token)
// cy.server() --server() is not required with cy.request()
var NEWURL = Cypress.config().baseUrl + TASK_URI
cy.request({
method: 'GET',
url: NEWURL,
failOnStatusCode: false,
headers: {
'x-auth-token': token
}
}).as('fetchTaskDetails');
cy.log("local: " + token);
cy.get('@fetchTaskDetails').then(function (response) {
const taskStatus = response.body.task.status;
cy.log('task status: ' + taskStatus);
expect(taskStatus).to.match(regex);
cy.wrap(taskStatus); // --this is a promise
});
// return taskStatus --not a promise
})
您将可以使用 then()
在测试中获取taskStatus:
You will be able to get taskStatus in your test using then()
:
cy.pollTask(TASK_URI, token).then(taskStatus => {
// do something with taskStatus
});
这篇关于如何从赛普拉斯自定义命令返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!