0
votes

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

1 Answers

0
votes

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