How to return a value from Cypress custom command

末鹿安然 提交于 2021-01-29 13:42:55

问题


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

回答1:


You must return a Promise. Here's a simple get/set example from Cypress Custom Commands documentation.

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

You will be able to get taskStatus in your test using then():

cy.pollTask(TASK_URI, token).then(taskStatus => {
    // do something with taskStatus
});


来源:https://stackoverflow.com/questions/61478500/how-to-return-a-value-from-cypress-custom-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!